为什么将整个HttpResponseMessage序列化? [英] Why is the entire HttpResponseMessage serialized?

查看:97
本文介绍了为什么将整个HttpResponseMessage序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要执行此Web API

Why does this Web API implementation

[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响应?

How can I make the Web API return an HTTP response like below?

200 OK
Content-Type: text/plain

hello

我最后要做的是返回JSON和其他带有各种状态代码的格式,因此以下代码无济于事.

What I want to do finally is return JSON and other formats with various status codes, so the following code wouldn't help me as an answer.

[HttpGet("hello")]
public string Hello()
{
    return "hello";
}

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

(I'm new to ASP.NET and other Microsoft technologies.)

推荐答案

最近我也遇到了同样的情况.原因是由于某种原因,有两个对System.Net.Http.dll程序集的引用:一个来自GAC,另一个来自我的项目.

I had the same happen to me recently. The reason was that, for some reason, there was two references to the System.Net.Http.dll assembly: one from the GAC and one local copy from my project.

在一个有趣的情况下,您发送的HttpResponseMessage的类型与ASP.NET期望的HttpResponseMessage的类型不同,这就是为什么在处理消息时,它只是将其序列化为JSON.

It results in an interesting case where the type of HttpResponseMessage you send isn't the same type of HttpResponseMessage ASP.NET expects, and that's why instead on processing the message, it just serializes it as JSON.

为此找到的解决方案是从NuGet安装System.Net.Http包,并确保在Web.config上正确生成绑定重定向,以便仅使用依赖项的一个副本.

The solution I found for this is to install the System.Net.Http package from NuGet, and ensure that the binding redirect is generated correctly on the Web.config, so that only one copy of the dependency is used.

这篇关于为什么将整个HttpResponseMessage序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆