为什么整个HttpResponseMessage序列化?

Tak*_*aki 5 c# asp.net asp.net-web-api

为什么要使用这个Web API

[HttpGet("hello")]
public HttpResponseMessage Hello()
{
    var res = new HttpResponseMessage(HttpStatusCode.OK);
    res.Content = new StringContent("hello", Encoding.UTF8, "text/plain");
    return res;
}
Run Code Online (Sandbox Code Playgroud)

返回

{
  "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
}
Run Code Online (Sandbox Code Playgroud)

代替

hello
Run Code Online (Sandbox Code Playgroud)

如何让Web API返回如下所示的HTTP响应?

200 OK
Content-Type: text/plain

hello
Run Code Online (Sandbox Code Playgroud)

我最终想要做的是返回JSON和其他具有各种状态代码的格式,因此以下代码不能帮助我作为答案.

[HttpGet("hello")]
public string Hello()
{
    return "hello";
}
Run Code Online (Sandbox Code Playgroud)

(我是ASP.NET和其他Microsoft技术的新手.)

Adi*_*dil 0

有趣的是,如果我在 ASP.NET 4 上尝试你的代码

public HttpResponseMessage Hello()
{
    var res = new HttpResponseMessage(HttpStatusCode.OK);
    res.Content = new StringContent("hello", Encoding.UTF8, "text/plain");
    return res;
}
Run Code Online (Sandbox Code Playgroud)

我得到了回应,这是我所期望的。


标题:

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
...
X-Powered-By: ASP.NET
Date: ...
Run Code Online (Sandbox Code Playgroud)

身体

hello
Run Code Online (Sandbox Code Playgroud)

根据情况,您可以依赖客户端来指定它可以接受的内容,也可以指定服务器始终抛出 json。

我通常有自定义请求/响应对象,并将其扔回客户端。例如

public CustomResponse Get()
{
    CustomResponse response = new CustomResponse();

    // some work
    response.TestProperty1 = "Test Value 1";
    response.TestProperty2 = "Test value 2";

    return response;
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您的 API 尊重您的客户接受的内容。因此,如果客户端设置请求标头“Accept:application/xml”,那么它将返回 xml 或 json(如果是 json.xml)。请参阅下面的 fiddler 请求的屏幕截图。

根据记忆,我认为您还可以在服务器上指定始终发送 json。

客户端接受 JSON

客户端接受 XML

希望这可以帮助!