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).
2
Answers
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.By default, the framework doesn’t allow POST requests to have an empty body. You can change this behavior in two ways:
.AddControllers()
to.AddControllers(opt => opt.AllowEmptyInputInBodyModelBinding = true)
.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.