Thursday, July 12, 2018

Model Binding .Net Core

Model binding is the process whereby the MVC or WebApi pipeline takes the raw HTTP request and converts that into the arguments for an action method invocation on a controller.

It is important to note that if the model binders fail to bind the parameters for some reason, they will not throw an error, instead you will receive a default object, with none of the properties set, which is the behaviour we showed earlier.

In order to bind the JSON correctly in ASP.NET Core, you must modify your action to include the attribute [FromBody] on the parameter. This tells the framework to use the content-type header of the request to decide which of the configured IInputFormatters to use for model binding.

So just always include [FromBody]?

So if you were thinking you can just always use [FromBody] in your methods, hold your horses. Lets see what happens when you hit your new endpoint with a x-www-url-formencoded request:

Oh dear. In this case, we have specifically told the ModelBinder to bind the 
body of the post, which is FirstName=Andrew&LastName=Lock&Age=31, using an IInputFormatter. Unfortunately, the JSON formatter is the only formatter we have and that doesn't match our content type, so we get a 415 error response.

In order to specifically bind to the form parameters we can either remove the FromBody attribute or add the alternative FromForm attribute, both of which will allow our form data to be bound but again will prevent the JSON binding correctly.

No comments: