为什么 ASP.Net core returns 400 默认情况下如果请求不是 Json 而它应该

Why ASP.Net core returns 400 by default if the request is not Json when it should

根据 Microsoft and Mozilla 文档,415 状态代码是:

微软:

HTTP_STATUS_UNSUPPORTED_MEDIA

415

The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.

Mozilla

The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format.

为什么如果我将内容类型设置为 JSON 并发送一个 XML 作为请求正文,我应该得到 415 而默认得到 400?

当请求不是有效的 JSON 格式时,获取 415 的最佳方法是什么?我使用资源过滤器实现了它,但我认为每次读取请求主体两次是一种浪费 if 还有其他方法。

这是我的代码:

public class MyResourceFilter:Attribute, IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        context.HttpContext.Request.EnableRewind();
        var requestBodyText = new StreamReader(context.HttpContext.Request.Body).ReadToEnd();
        context.HttpContext.Request.Body.Position = 0;
        try
        {
            JsonConvert.DeserializeObject<object>(requestBodyText);
        }
        catch (Exception e)
        {
            context.Result= new UnsupportedMediaTypeResult();
        }
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
    }
}

在这种情况下 return 415 是不正确的。该状态代码字面意思是服务器不支持 mime 类型,在本例中为 application/json。服务器非常确实支持该类型,因此它不会return 415。400 Bad Request 是 return 的正确响应状态代码,因为你告诉它是 JSON,但你发送了 XML,即 你提出了错误的请求