cvb*_*ros 11 html c# content-negotiation asp.net-web-api
在阅读了关于如何使用Web API 2返回HTML的博客文章之后,我想根据请求发送的标题以某种方式将其"连线" 到我的网上.IHttpActionResultIHttpActionResultApiControllerAccept
给定具有与此类似的签名的控制器操作:
public MyObject Get(int id)
{
return new MyObject();
}
Run Code Online (Sandbox Code Playgroud)
如果请求指定了Accept: text/html,则IHttpActionResult应该使用它来返回HTML.那可能吗?此外,对于这个内容协商管道如何为json或xml(具有内置支持)工作的一些见解将不胜感激.
Kir*_*lla 13
如果我们继续讨论IHttpActionResult一下,Web API中的内容协商过程是通过格式化程序来驱动的.因此,您需要创建一个新的格式化程序来处理媒体类型text/html.
Web API公开了它用于内容协商的默认算法,该算法DefaultContentNegotiator是服务的实现IContentNegotiator.
现在,这个协商算法可以通过Web API自动运行,就像在下列情况下一样:
用法#1:
public MyObject Get(int id)
{
return new MyObject();
}
Run Code Online (Sandbox Code Playgroud)
要么
您可以自己手动运行协商,如下所示:
用法#2:
public HttpResponseMessage Get()
{
HttpResponseMessage response = new HttpResponseMessage();
IContentNegotiator defaultNegotiator = this.Configuration.Services.GetContentNegotiator();
ContentNegotiationResult negotationResult = defaultNegotiator.Negotiate(typeof(string), this.Request, this.Configuration.Formatters);
response.Content = new ObjectContent<string>("Hello", negotationResult.Formatter, negotationResult.MediaType);
return response;
}
Run Code Online (Sandbox Code Playgroud)
关于IHttpActionResults:
在以下场景中,Ok<>是一种生成类型实例的快捷方法
OkNegotiatedContentResult<>.
public IHttpActionResult Get()
{
return Ok<string>("Hello");
}
Run Code Online (Sandbox Code Playgroud)
事情是这种OkNegotiatedContentResult<>类型与上面的用法#2场景类似.即他们在内部管理谈判者.
总而言之,如果您计划支持text/html媒体类型,那么您需要编写自定义格式化程序并将其添加到Web API的格式化程序集合中,然后当您使用Ok<string>("Hello")Accept标头时text/html,您应该看到响应text/html.希望这可以帮助.