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



我的Web API控制器在其一种方法之一中处理某些第三方类

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

它是使用自定义媒体类型formatter解析的,并具有自己的媒体类型" application/json castureType"。

问题是,错误指定了参数内容类型(例如"应用程序/JSON")。Web API使用另一个格式化器来解析请求主体,然后当它尝试创建第三型PartyCustomType的实例时,它将失败一些内部验证并抛出NullReferenceExcept。

我如何告诉Web API在内容类型错误时不要尝试解析请求主体?

编辑:在评论中建议我创建了一个中间件类,现在所有的请求都被捕获到那里,我需要此验证才能仅适用于一个。我认为我可以检查request.path我的中间件,并且只有在与我的请求相对应的情况下行动,但这似乎不是很好的解决方案。

另一个编辑最后看起来像这样:

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);
        }
    }
}

有更好的方法吗?

当返回类型为ihttpactionResult时,您可以使用构建的响应类型中的内置,例如ok(),badrequest(),badrequest()或notfound()或notfound(),并且在其余的状态代码中,您可以使用statuscode(httpstatuscode statuscode)方法。

return StatusCode(HttpStatusCode.UnsupportedMediaType);

最新更新