Reputation: 953
We are migrating a site from ASP MVC .Net Framework to .Net Core. In many cases we do ajax POST requests from the page to the Controller:
var request = { Name: "bar" };
$.ajax({
url: "/Home/foo",
type: "POST",
data: JSON.stringify(request),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log();
}
});
[HttpPost]
public async Task<JsonResult> foo(FooRequest request)
{
//request.Name is empty
return Json(new { msg = "Success" });
}
public class FooRequest
{
public string Name { get; set; }
}
This all works in .Net Framework, but fails in Core were all properties of the received object are null.
I've tried using both AddJsonOptions
:
services.AddControllersWithViews()
.AddJsonOptions(option =>
{
option.JsonSerializerOptions.PropertyNamingPolicy = null;
option.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
...and AddNewtonsoftJson
:
services.AddControllersWithViews()
.AddNewtonsoftJson(option =>
{
option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
});
...but none of them works.
I get the same behavior calling the endoint from Postman (request.Name is null):
POST /home/foo HTTP/1.1
Host: localhost:44393
Content-Type: application/json
{ "Name": "bar" }
I've also tried to serializing the request:
var request = { Name: "bar" };
$.ajax({
url: "/Home/foo",
type: "POST",
data: request,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log();
}
});
...but with the same result
Upvotes: 3
Views: 1287
Reputation: 23945
Try adding the FromBodyAttribute
to your parameter:
[HttpPost]
public async Task<JsonResult> foo([FromBody] FooRequest request)
{
//request.Name is empty
return Json(new { msg = "Success" });
}
You can omit this attribute, if you decorate your controller with the ApiControllerAttribute
Upvotes: 3