0

I have upgraded my project to MVC Core 2.2 and suddenly all WEB Api endpoints that received the parameters from query or form data started to return 415 Unsupported Media Type.

Here is example method in my web apis

[HttpPut()]
public int Add(Entities.UserMember user)
{
    Service.UserCreate(user);
    return user.Id;
}

This worked perfectly fine with MVC Core 2.1 accepting the both from url and form. Now it seems that i need to specify a specific attribute per each endpoint and it seems that only one can be used. Is there any way to allow same behavior or i need to change my code and add FromQuery() to all of my api methods ?

KJSR
  • 1,679
  • 6
  • 28
  • 51
NullReference
  • 862
  • 1
  • 11
  • 27
  • I am confused? Are you having issue with params being passed to the API? – KJSR Jul 25 '19 at 13:44
  • Basically without the attributes specifying how the parameters are passed to the api function i get 415 status code. As i said it previously both methods work either frombody or fromurl, now the functions will only be called if one of the attributes specified. – NullReference Jul 25 '19 at 13:47
  • Are you using `HttpClient` to post to your API? – KJSR Jul 25 '19 at 13:53
  • Tried both httpclient and postman and the result is the same. – NullReference Jul 25 '19 at 13:56
  • This might help you: https://stackoverflow.com/questions/44538772/asp-net-core-form-post-results-in-a-http-415-unsupported-media-type-response – Martin Staufcik Jul 25 '19 at 14:24

1 Answers1

1

For this issue, it is caused by the [ApiController] feature.

In ASP.NET Core 2.1, collection type parameters such as lists and arrays are incorrectly inferred as [FromQuery]. The [FromBody] attribute should be used for these parameters if they are to be bound from the request body. This behavior is corrected in ASP.NET Core 2.2 or later, where collection type parameters are inferred to be bound from the body by default.

Reference: Binding source parameter inference

There are two options for you.

  1. Remove [ApiController] from the Controller
  2. Set SuppressInferBindingSourcesForParameters by true like

    services.Configure<ApiBehaviorOptions>(options => {
        options.SuppressInferBindingSourcesForParameters = true;
    });
    
Edward
  • 28,296
  • 11
  • 76
  • 121