如何使用 ApiController 返回原始字符串? [英] How to return raw string with ApiController?
问题描述
我有一个提供 XML/JSON 的 ApiController,但我希望我的一个操作返回纯 HTML.我尝试了以下但它仍然返回 XML/JSON.
I have an ApiController that serves XML/JSON, but I would like one of my actions to return pure HTML. I tried the below but it still return XML/JSON.
public string Get()
{
return "<strong>test</strong>";
}
这是上面的返回:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"><strong>test</strong></string>
有没有办法只返回纯的、未转义的文本,甚至没有周围的 XML 标签(可能是不同的操作属性返回类型)?
Is there a way to return just the pure, unescaped text without even the surrounding XML tags (maybe a different return type of action attribute)?
推荐答案
您可以让您的 Web Api 操作返回一个 HttpResponseMessage
,您可以完全控制其内容.在您的情况下,您可以使用 StringContent 并指定正确的内容类型:
You could have your Web Api action return an HttpResponseMessage
for which you have full control over the Content. In your case you might use a StringContent and specify the correct content type:
public HttpResponseMessage Get()
{
return new HttpResponseMessage()
{
Content = new StringContent(
"<strong>test</strong>",
Encoding.UTF8,
"text/html"
)
};
}
或
public IHttpActionResult Get()
{
return base.ResponseMessage(new HttpResponseMessage()
{
Content = new StringContent(
"<strong>test</strong>",
Encoding.UTF8,
"text/html"
)
});
}
这篇关于如何使用 ApiController 返回原始字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!