[英]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.