Is there a way to disable the default 415 ( Unsupported Media Type
) response ASP.NET Core returns for the missing Content-Type
header? Should it matter if the body is empty anyway?
[ApiController]
public class UserController : ControllerBase
{
// This will return a 415 response if called with empty body and no `Content-Type` header.
[HttpPost]
[Route("/api/v2/users:search")]
public async Task<IActionResult> SearchUsers(
[FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] SearchUsersCommand? body)
{
throw new NotImplementedException();
}
}
Actually I didn't find the way to disable it. However, I found the solution in another question from below link :
How to disable default error response for Api Versioning
Also, to fix the error, I suggest the following solution:
For forms, use the FromForm attribute instead of the FromBody attribute.
The below controller works with ASP.NET Core 1.1:
public class MyController : Controller
{
[HttpPost]
public async Task<IActionResult> Submit([FromForm] MyModel model)
{
//...
}
}
The best workaround I could find is to implement a custom MVC convention. It adds a filter to every controller to set the default content type if it's not set yet.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Filters;
namespace MyWebApi
{
internal class AllowMissingContentTypeForEmptyBodyConvention : IActionModelConvention
{
public void Apply(ActionModel action)
{
action.Filters.Add(new AllowMissingContentTypeForEmptyBodyFilter());
}
private class AllowMissingContentTypeForEmptyBodyFilter : IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
if (!context.HttpContext.Request.HasJsonContentType() && context.HttpContext.Request.ContentLength == 0)
{
context.HttpContext.Request.ContentType = "application/json";
}
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
// Do nothing
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.