[英]Owin/WebApi force to to accept only application/json Accept and Content-Type headers
I need to configure my Owin self-host to accept only application/json
Accept and Content-Type headers. 我需要将Owin自托管服务器配置为仅接受
application/json
Accept和Content-Type标头。 For any other Accept
received from client (for example application/xml
) i want to return an Http 415 Unsupported Media Type). 对于从客户端收到的任何其他
Accept
(例如application/xml
),我想返回Http 415不支持的媒体类型。
I've tried all solutions but none of them seem to work. 我已经尝试了所有解决方案,但似乎都不起作用。 http://www.strathweb.com/2013/06/supporting-only-json-in-asp-net-web-api-the-right-way/
http://www.strathweb.com/2013/06/supporting-only-json-in-asp-net-web-api-the-right-way/
I tried to clear all formatters in my HttpConfiguration
and add only the Json one: 我试图清除
HttpConfiguration
所有格式化程序,并仅添加Json一个:
configuration.Formatters.Clear();
configuration.Formatters.Add(new JsonMediaTypeFormatter());
Doesn't work, it still returns 200 Ok
for any media type. 不起作用,对于任何媒体类型,它仍返回
200 Ok
。
I've tried to replace the DefaultContentNegotiator
with my own JsonContentNegotiator
as in the example from the link above, still with no luck. 我试图用我自己的
JsonContentNegotiator
替换DefaultContentNegotiator
,如上面链接中的示例所示,仍然没有运气。
I ended up with the solution that i'm myself verifying the headers in my Controller. 我最终得到的解决方案是,我自己要验证Controller中的标头。 But that's a pretty ugly solution.
但这是一个非常丑陋的解决方案。 Is there any way to achieve this with webapi?
有什么办法可以使用webapi做到这一点吗?
Did you try using delegate handlers ? 您是否尝试过使用委托处理程序 ?
public class MediaTypeDelegatingHandler: DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Headers.Accept.Contains(MediaTypeWithQualityHeaderValue.Parse("application/json")) == false)
{
return request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
return await base.SendAsync(request, cancellationToken);
}
}
and 和
public static void Register(HttpConfiguration config)
{
config.MessageHandlers.Add(new MediaTypeDelegatingHandler());
}
I haven't tried the code but if you don't have a solution yet you can give it a try. 我没有尝试过代码,但是如果您还没有解决方案,可以尝试一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.