gpt4 book ai didi

c# - 返回 HTML 的内容协商

转载 作者:技术小花猫 更新时间:2023-10-29 12:51:20 26 4
gpt4 key购买 nike

看完this blog post关于如何使用 IHttpActionResultWeb API 2 返回 HTML,我想以某种方式将此 IHttpActionResult“连接”到我的 ApiController 基于随请求发送的 Accept header 。

给定具有与此类似签名的 Controller 操作:

public MyObject Get(int id)
{
return new MyObject();
}

如果请求指定了 Accept: text/html,则此 IHttpActionResult 应该用于返回 HTML。那可能吗?此外,如果能深入了解此内容协商管道如何适用于 json 或 xml(具有内置支持),我们将不胜感激。

最佳答案

如果我们继续讨论 IHttpActionResult暂时搁置一下,Web API 中的内容协商过程是通过格式化程序驱动的。所以你需要创建一个新的格式化程序来处理媒体类型 text/html .

Web API 公开了它用于内容协商的默认算法 DefaultContentNegotiator这是服务的实现 IContentNegotiator .

现在这种协商算法可以通过 Web API 自动为您运行,例如在以下情况下:

用法 # 1:

public MyObject Get(int id)
{
return new MyObject();
}

您可以自己手动运行协商,如下所示:

用法#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;
}

关于 IHttpActionResults:
在以下场景中,Ok<>是生成类型实例的快捷方法 OkNegotiatedContentResult<> .

public IHttpActionResult Get()
{
return Ok<string>("Hello");
}

事情是这个OkNegotiatedContentResult<> type 做的事情与上面的Usage # 2 场景类似。即他们在内部运行谈判者。

总而言之,如果您打算支持text/html media type 那么你需要编写一个自定义格式化程序并将其添加到 Web API 的格式化程序集合中,然后当你使用 Ok<string>("Hello") 时接受 header 为 text/html ,您应该会在 text/html 中看到响应.希望这会有所帮助。

关于c# - 返回 HTML 的内容协商,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21468163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com