简体   繁体   English

ASP .NET Web API 如何在不支持的媒体类型上返回错误

[英]ASP .NET Web API How to return error on unsupported media type

My Web API controller deals with some third party class in one of its methods我的 Web API 控制器在其方法之一中处理某些第三方类

[HttpPost]
public IHttpActionResult CreateJob([FromBody] ThirdPartyCustomType item)
{
  //Something useful done here
}

It is parsed using custom media type formatter and has it's own media type "application/json+customType".它使用自定义媒体类型格式化程序进行解析,并拥有自己的媒体类型“application/json+customType”。

The problem is that when parameter content type is specified incorrectly(for example "application/json").问题是当参数内容类型指定不正确时(例如“application/json”)。 Web API uses another formatter to parse request body and then when it tries to create instance of ThirdPartyCustomType it fails some internal validation and throws NullReferenceException. Web API 使用另一个格式化程序来解析请求正文,然后当它尝试创建 ThirdPartyCustomType 的实例时,它会失败一些内部验证并抛出 NullReferenceException。

How can I tell Web API not to try and parse request body when content type is wrong?当内容类型错误时,如何告诉 Web API 不要尝试解析请求正文?

EDIT: As guys in comments suggested I created a middleware class, now the thing is that all requests are getting caught there and I need this validation to work only for one.编辑:正如评论中的人建议我创建了一个中间件类,现在的问题是所有请求都在那里被捕获,我需要此验证仅适用于一个。 I think that I can check Request.Path in my middleware and act only if it corresponds to my request but that does not seems like good solution.我认为我可以检查中间件中的 Request.Path 并仅在它符合我的请求时才采取行动,但这似乎不是一个好的解决方案。

Another edit Finally it looks like this:另一个编辑最后它看起来像这样:

public class ContentTypeCheckMiddleWare : OwinMiddleware
{
    public ContentTypeCheckMiddleWare(OwinMiddleware next) : base(next)
    {
    }

    public async override Task Invoke(IOwinContext context)
    {
        if (context.Request.Path.Value.EndsWith("myRouteSuffix") && context.Request.Method == "POST")
        {
            var contentType = context.Request.ContentType;

            if (contentType != "application/json+customType")
            {
                context.Response.StatusCode = 416;
                await context.Response.WriteAsync(
                    "Invalid content type.");
            }
        }
        else
        {
            await Next.Invoke(context);
        }
    }
}

Is there any better way?有没有更好的办法?

当返回类型为 IHttpActionResult 时,您可以使用内置响应类型,例如 Ok()、BadRequest() 或 NotFound(),对于其余状态代码,您可以使用 StatusCode(HttpStatusCode statuscode) 方法。

return StatusCode(HttpStatusCode.UnsupportedMediaType);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 不支持的媒体类型 ASP.NET Core Web API - Unsupported media type ASP.NET Core Web API ASP.NET 核心 Web API 不支持的媒体类型 - ASP.NET Core Web API unsupported Media type POST到内容类型为x-www-form-urlencoded的asp.net Web API会引发错误415不支持的媒体类型 - POST to asp.net web api with content type x-www-form-urlencoded raises error 415 unsupported media type 尝试将FormData从Angular 5应用程序发送到ASP.NET 4.6.1 Web API:出现“不受支持的媒体类型”错误 - Trying to send FormData from Angular 5 app to ASP.NET 4.6.1 Web API : getting an “unsupported media type” error ASP.Net Core Web API:GET 请求不支持的媒体类型 - ASP.Net Core Web API: Unsupported Media Type on GET Request 415(不支持的媒体类型)将数据从 angular9 传递到 asp.net web api - 415(unsupported media type) when passing data from angular9 to asp.net web api Web API ASP.NET 核心发布请求 415 不支持的媒体类型 - Web API ASP.NET Core Post Request 415 Unsupported Media Type API 在 ASP.NET 核心中返回不受支持的媒体类型 - API returning unsupported media type in ASP.NET Core 远程服务器返回错误:(415)在asp.net中使用API​​的不支持的媒体类型 - The remote server returned an error: (415) Unsupported Media Type using API in asp.net 415到.NET Web API的不支持的媒体类型 - 415 Unsupported Media Type on POST to .NET Web API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM