Home > Net >  ASP.NET requires media type even if there is no request body
ASP.NET requires media type even if there is no request body

Time:09-24

I have the HTTP endpoint with the optional body (OrderRequest):

[HttpPost]
public async Task<ActionResult> Index(OrderRequest? request = null)
{
    //...
}

If sending a request in which Content-Type header is not specified, then 415 (Unsupported Media Type) error will appear.

What can I do to allow requests without a body and media type?


Of course, to solve it I could just add the appropriate media type on the client side. But the problem is that the previous version of this endpoint didn't require any request body and therefore media type was not required as well. So in order to ensure backward compatibility, I need to configure this endpoint to be able to accept requests as earlier (without a request body and media type).

CodePudding user response:

By default, the framework doesn't allow POST requests to have an empty body. You can change this behavior in two ways:

  1. Globally. In this scenario, in your Program.cs, change .AddControllers() to .AddControllers(opt => opt.AllowEmptyInputInBodyModelBinding = true).
  2. This endpoint only. In this case, change the method declaration to Index([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] OrderRequest? request = null).

However, this will not fix the issue where the framework simply returns 415 Unsupported Media Type.

I dig a bit into this and apparently one of the ways to change this behavior is by creating a filter, like it is said here.

There is a GitHub issue on the aspnetcore repository where they discussed this situation. There is also a open pull request to support this behavior.

CodePudding user response:

To fix the issue, two action methods should be created. The first one is intended for requests without body, and the second one is the opposite.

After that, add Consumes attribute to the second method. This attribute filters requests for specified media types. As a result, all other requests with different media types or without ones will go to another action method.

[HttpPost]
public async Task<ActionResult> Index() => Index(null);

[HttpPost]
[Consumes("application/json")]
public async Task<ActionResult> Index(OrderRequest? request)
{
    //...
}
  • Related