简体   繁体   English

将内容放在 HttpResponseMessage 对象中?

[英]Put content in HttpResponseMessage object?

Several months ago, Microsoft decided to change up the HttpResponseMessage class.几个月前,Microsoft 决定更改 HttpResponseMessage 类。 Before, you could simply pass a data type into the constructor, and then return the message with that data, but not anymore.以前,您可以简单地将数据类型传递给构造函数,然后返回带有该数据的消息,但现在不行了。

Now, you need to use the Content property to set the content of the message.现在,您需要使用 Content 属性来设置消息的内容。 The problem is that it is of type HttpContent, and I can't seem to find a way to convert a string, for example, to HttpContent.问题是它是 HttpContent 类型的,我似乎找不到将字符串转换为 HttpContent 的方法。

Does anyone know how to deal with this issue?有谁知道如何处理这个问题? Thanks a lot.非常感谢。

For a string specifically, the quickest way is to use the StringContent constructor具体来说,对于字符串,最快的方法是使用StringContent构造函数

response.Content = new StringContent("Your response text");

There are a number of additional HttpContent class descendants for other common scenarios.对于其他常见场景,还有许多附加的HttpContent 类后代

You should create the response using Request.CreateResponse :您应该使用Request.CreateResponse创建响应:

HttpResponseMessage response =  Request.CreateResponse(HttpStatusCode.BadRequest, "Error message");

You can pass objects not just strings to CreateResponse and it will serialize them based on the request's Accept header.您不仅可以将对象传递给 CreateResponse 字符串,而且它会根据请求的 Accept 标头对它们进行序列化。 This saves you from manually choosing a formatter.这使您免于手动选择格式化程序。

Apparently the new way to do it is detailed here:显然,这里详细介绍了新的方法:

http://aspnetwebstack.codeplex.com/discussions/350492 http://aspnetwebstack.codeplex.com/discussions/350492

To quote Henrik,引用亨利克的话,

HttpResponseMessage response = new HttpResponseMessage();

response.Content = new ObjectContent<T>(T, myFormatter, "application/some-format");

So basically, one has to create a ObjectContent type, which apparently can be returned as an HttpContent object.所以基本上,必须创建一个 ObjectContent 类型,它显然可以作为 HttpContent 对象返回。

The easiest single-line solution is to use最简单的单行解决方案是使用

return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( "Your message here" ) };

For serialized JSON content:对于序列化的 JSON 内容:

return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( SerializedString, System.Text.Encoding.UTF8, "application/json" ) };

对于任何 T 对象,您可以执行以下操作:

return Request.CreateResponse<T>(HttpStatusCode.OK, Tobject);

You can create your own specialised content types.您可以创建自己的专业内容类型。 For example one for Json content and one for Xml content (then just assign them to the HttpResponseMessage.Content):例如,一个用于 Json 内容,一个用于 Xml 内容(然后将它们分配给 HttpResponseMessage.Content):

public class JsonContent : StringContent
{
    public JsonContent(string content)
        : this(content, Encoding.UTF8)
    {
    }

    public JsonContent(string content, Encoding encoding)
        : base(content, encoding, "application/json")
    {
    }
}

public class XmlContent : StringContent
{
    public XmlContent(string content) 
        : this(content, Encoding.UTF8)
    {
    }

    public XmlContent(string content, Encoding encoding)
        : base(content, encoding, "application/xml")
    {
    }
}

Inspired by Simon Mattes' answer, I needed to satisfy the IHttpActionResult required return type of ResponseMessageResult .受 Simon Mattes 回答的启发,我需要满足IHttpActionResult所需的ResponseMessageResult返回类型。 Also using nashawn's JsonContent , I made this :也使用 nashawn 的JsonContent ,我做了这个:

return new System.Web.Http.Results.ResponseMessageResult(
    new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
    {
        Content = new JsonContent(JsonConvert.SerializeObject(contact, Formatting.Indented))
    });

See nashawn's answer for JsonContent .请参阅 nashawn 对JsonContent的回答。

No doubt that you are correct Florin.毫无疑问,你是正确的弗洛林。 I was working on this project, and found that this piece of code:我在做这个项目,发现这段代码:

product = await response.Content.ReadAsAsync<Product>();

Could be replaced with:可以替换为:

response.Content = new StringContent(string product);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM