【发布时间】:2015-09-19 07:55:28
【问题描述】:
为什么要实现这个 Web API
[HttpGet("hello")]
public HttpResponseMessage Hello()
{
var res = new HttpResponseMessage(HttpStatusCode.OK);
res.Content = new StringContent("hello", Encoding.UTF8, "text/plain");
return res;
}
返回
{
"Version":{
"Major":1,
"Minor":1,
"Build":-1,
"Revision":-1,
"MajorRevision":-1,
"MinorRevision":-1
},
"Content":{
"Headers":[{
"Key":"Content-Type",
"Value":["text/plain; charset=utf-8"]
}]
},
"StatusCode":200,
"ReasonPhrase":"OK",
"Headers":[],
"RequestMessage":null,
"IsSuccessStatusCode":true
}
而不是
hello
?
如何让 Web API 返回如下 HTTP 响应?
200 OK
Content-Type: text/plain
hello
我最终想要做的是返回带有各种状态码的 JSON 和其他格式,所以下面的代码对我没有帮助。
[HttpGet("hello")]
public string Hello()
{
return "hello";
}
(我是 ASP.NET 和其他 Microsoft 技术的新手。)
【问题讨论】:
-
我遇到了类似的问题。我正在返回 HTML,设置正确的内容类型,然后返回一个序列化的 HttpResponseMessage。我创建了一个全新的 WebApi 4.6.1 项目,一对一复制代码,运行测试,结果得到一个 HTML 页面。我想知道它是否与中间件(OWIN)在它消失之前更改内容类型有关。
标签: c# asp.net asp.net-web-api