I used to just post simple json objects to ASP.NET MVC controllers and the binding engine would parse the body out into the method's simple parameters:
{
"firstname" : "foo",
"lastname" : "bar"
}
and I could have a MVC controller like this:
public method Blah(string firstname, string lastname) {}
And firstname and lastname would automatically be pulled from the Json object and mapped to the simple parameters.
I've moved a backend piece to .NET Core 5.0 with the same method signatures, however, when I post the same simple JSON object, my parameters are null. I even tried doing [FromBody] on each parameter but they would still be null. It wasn't until I created an extra class that contained the parameter names would the model binding work:
public class BlahRequest
{
public string firstname { get; set;}
public string lastname { get; set; }
}
And then I have to update my method signature to look like this:
public method Blah([FromBody]BlahRequest request) { }
And now, the request has the properties firstname and lastname filled out from the post request.
Is there a model binder setting where I can go back to binding from a simple Json object to the method's parameters? Or do I have to update all my method signatures to contain a class with properties?
How the web api method is called
The original application is written in Angular but I can recreate it with a simple Fiddler request:
POST https://localhost:5001/Blah/Posted HTTP/1.1
Host: localhost:5001
Connection: keep-alive
Accept: application/json, text/plain, */*
Content-Type: application/x-www-form-urlencoded
{"firstname":"foo","lastname":"bar"}
In previous versions of the .Net framework, the controller's method would parse those values automatically. Now, on core, it requires a model to be passed in. I've tried application/json, multipart/form-data, and application/x-www-form-urlencoded as the Content-type and they all end up with null values.
Smallest .Net Core project
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services){
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
[Route("[controller]/[action]")]
public class BlahController : ControllerBase {
public object Posted(string firstname, string lastname) {
Console.WriteLine(firstname);
Console.WriteLine(lastname);
return true;
}
}