Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax Calls with Fetch API in .NET Core 3.1

I just migrated to .NET Core 3.1 and among the different things I had to update I can't get my ajax calls to work.

When I make an ajax call, none of the data binds to the object parameter in my action.

This is how I am making the call in my razor page

fetch('/Administration/UpdateUserStatus', {
    method: 'POST',
    credentials: 'include',
    headers: {
        'Content-Type': 'application/json',
        'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
    },
    body: JSON.stringify(data)
})

And my controller action

[HttpPost]
public IActionResult UpdateUserStatus([FromBody]User user) {
    ...
}

In my example code above, debugging the code I can see that user comes in as null, so the data from the ajax call does not bind to the User object.

If I remove [FromBody], user does not come in as null anymore, but the data still doesn't bind. All the properties as either null or the default value.

Everything was working fine in .NET Core 2.1.

Is it something I need to add in Startup.cs? Maybe a new configuration I am missing?

Thanks

like image 427
esausilva Avatar asked Dec 18 '19 20:12

esausilva


1 Answers

I solved my issue. Json.NET was removed from .NET Core 3.0 so I had to add a reference to package Microsoft.AspNetCore.Mvc.NewtonsoftJson (NuGet) then under the ConfigureServices method add .AddNewtonsoftJson() to Razor Pages, like so

services.AddRazorPages().AddNewtonsoftJson();

After that, everything is working as before.

Docs

like image 86
esausilva Avatar answered Sep 23 '22 02:09

esausilva