Mapping json request body properties in ASP.NET Core API Controllers
Posted on 2017-10-16

FromBodyProperty

FromBodyPropertyAttribute lets you bind ASP.NET Core MVC Controller action parameters from raw request body json content properties.
[FromBody] allows you to bind a single parameter with data from the request body, with multiple values you will need to use a complex object.
[FromBodyProperty] allows you to bind multiple parameters with data from the request body:
Example controller action with multiple parameters:
public MultiplyResponse Multiply([FromBodyProperty] int x, [FromBodyProperty] int y)
The name of the action parameters are specified in the request body data:
{ "x": 2, "y": 5 }

How to use

Setup

In Startup.cs add (I)FromBodyPropertyModelBinderHelper & FromBodyPropertyJsonOptionsSetup
public void ConfigureServices(IServiceCollection services) {
	services.AddMvc();
	services.AddScoped<IFromBodyPropertyModelBinderHelper, FromBodyPropertyModelBinderHelper>();
	services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, FromBodyPropertyJsonOptionsSetup>());
}

Example controller

public class HomeController : Controller {
	public MultiplyResponse Multiply([FromBodyProperty] int x, [FromBodyProperty] int y) {
		return new MultiplyResponse() { Result = x * y };
	}
}

Example ajax request

var request = {
	x: 2,
	y: 5
}

var ajaxOptions = {
	url: "/Home/Multiply",
	dataType: "json",
	contentType: "application/json; charset=utf-8",
	type: "POST",
	data: JSON.stringify(request),
	success: function (data, textStatus, jqXHR) {
		alert(JSON.stringify(data, null, 4));
	},
	error: function (jqXHR, textStatus, errorThrown) {
		if (jqXHR.responseJSON) {
			alert(JSON.stringify(jqXHR.responseJSON, null, 4));
		}
		alert(textStatus);
	}
}
jQuery.ajax(ajaxOptions);

Demo project & code