Aspnetcore: Future Investments: Model Binding

Created on 14 Jul 2017  路  5Comments  路  Source: dotnet/aspnetcore

This is a place for tracking feedback and related bugs for scoping future investments in Model Binding.

Related Issues

6109 Question: call ModelBinding manually?

4437 Using validation without model state and controller

6014 Using DI as a factory and then model binding the object

4718 Add a secure binding option to model binders

1786 Support binding immutable types by binding to the constructor

area-mvc

Most helpful comment

I'd very much like to see manual model binding possible. I asked a long time go at #4811 and it seems there's still no way to accomplish such a thing without letting go of the advantages that model binding/validation brings.

Making model binding/validation not directly coupled to mvc will also be a super nice thing to have.

All 5 comments

I'd very much like to see manual model binding possible. I asked a long time go at #4811 and it seems there's still no way to accomplish such a thing without letting go of the advantages that model binding/validation brings.

Making model binding/validation not directly coupled to mvc will also be a super nice thing to have.

My temporary solution:
```C#
public class BaseController : Controller
{
public bool IsAjaxRequest()
{
if (Request == null)
{
throw new ArgumentNullException("request");
}

        return Request.Headers["X-Requested-With"] == "XMLHttpRequest";
    }

    public override async Task<bool> TryUpdateModelAsync(object model, Type modelType, string prefix)
    {
        if (model == null)
            model = Activator.CreateInstance(modelType);

        var result = await base.TryUpdateModelAsync(model, modelType, prefix);

        if (IsAjaxRequest())
        {
            try
            {
                using (var reader = new StreamReader(Request.Body))
                    JsonConvert.PopulateObject(reader.ReadToEnd(), model);

                return true && result;
            }
            catch (Exception exc)
            {
                var logger = HttpContext.RequestServices.GetService<ILogger<BaseController>>();
                if (logger != null)
                    logger.LogWarning(exc, "Error occurred while parsing '{0}' model.", modelType.Name);
            }

            return false;
        }
        else
        {
            return result;
        }
    }

    public virtual Task<bool> TryUpdateModelAsync(object model, Type modelType)
    {
        return TryUpdateModelAsync(model, modelType, null);
    }

    public override Task<bool> TryUpdateModelAsync<TModel>(TModel model, string prefix)
    {
        return TryUpdateModelAsync(model, typeof(TModel), prefix);
    }

    public override Task<bool> TryUpdateModelAsync<TModel>(TModel model)
    {
        return TryUpdateModelAsync(model, typeof(TModel));
    }

}
```
Please correct me if I am doing something weird in the code or there is some better solution.

@rynowak I think that your link to issue about support of binding immutable types is pointing to something unrelated. Anyway this feature would be highly appreciated especially when you design CQRS style API where commands and queries by definition should be immutable. BTW even EntityFramework supports deserializing entity via constructor nowadays so why MVC model binders still require public setters and by doing so discourage good practices like immutable messages/DTOs.

1786 Support binding immutable types by binding to the constructor

@rynowak, I would very much appreciate this feature. 馃槏 Now that System.Text.Json supports JsonConstructor in .net 5.0, it feels incomplete not having the ability for immutable complex types in asp net core.

@rynowak It looks like #1786 Support binding immutable types by binding to the constructor links to the wrong issue

Was this page helpful?
0 / 5 - 0 ratings