wmmhihaa
wmmhihaa

Reputation: 953

JSON serialization/deserialization not working when migrating to ASP.Net Core MVC

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:

js:

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();
    }
});

c# Controller:

[HttpPost]
public async Task<JsonResult> foo(FooRequest request)
{
    //request.Name is empty
    return Json(new { msg = "Success" });
}

c# Model:

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.

What do I need to do to get the same behavior in .Net Core as I do in .Net Framework?

Update

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

Answers (1)

Marco
Marco

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

Related Questions