为什么要实现这个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 技术的新手。)
最佳答案
我最近也遇到了同样的事情。原因是,出于某种原因,有两个对 System.Net.Http.dll 程序集的引用:一个来自 GAC,一个来 self 的项目的本地副本。
这会导致一个有趣的情况,即您发送的 HttpResponseMessage 类型与 ASP.NET 期望的 HttpResponseMessage 类型不同,这就是为什么在处理消息时,它只是将其序列化为 JSON。
我找到的解决方案是从 NuGet 安装 System.Net.Http 包,并确保在 Web.config 上正确生成绑定(bind)重定向,以便只使用一个依赖项副本。
关于c# - 为什么要序列化整个 HttpResponseMessage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32665773/