几个月前,微软决定改变HttpResponseMessage类。以前,您可以简单地将数据类型传递给构造函数,然后返回带有该数据的消息,但现在不一样了。
现在,您需要使用Content属性设置消息的内容。问题是它的类型是HttpContent,我似乎找不到一种方法来转换字符串,例如,到HttpContent。
有人知道如何处理这个问题吗? 非常感谢。
几个月前,微软决定改变HttpResponseMessage类。以前,您可以简单地将数据类型传递给构造函数,然后返回带有该数据的消息,但现在不一样了。
现在,您需要使用Content属性设置消息的内容。问题是它的类型是HttpContent,我似乎找不到一种方法来转换字符串,例如,到HttpContent。
有人知道如何处理这个问题吗? 非常感谢。
显然,新方法的详细说明如下:
http://aspnetwebstack.codeplex.com/discussions/350492
引用亨里克的话,
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new ObjectContent<T>(T, myFormatter, "application/some-format");
基本上,我们必须创建一个ObjectContent类型,它显然可以作为HttpContent对象返回。
对于字符串,最快的方法是使用StringContent构造函数
response.Content = new StringContent("Your response text");
对于其他常见场景,还有许多额外的HttpContent类后代。
您应该使用Request创建响应。连接CreateResponse:
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error message");
你可以把对象不仅仅是字符串传递给CreateResponse,它会根据请求的Accept报头对它们进行序列化。这样可以避免手动选择格式化程序。
您可以创建自己的专用内容类型,然后将它们分配给HttpResponseMessage。内容属性。
例如下面的一个JSON内容和一个XML内容:
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")
{
}
}
最简单的单线解决方案是使用
return new HttpResponseMessage( HttpStatusCode.OK ) {Content = new StringContent( "Your message here" ) };
对于序列化的JSON内容:
return new HttpResponseMessage( HttpStatusCode.OK ) {Content = new StringContent( SerializedString, System.Text.Encoding.UTF8, "application/json" ) };
受到Simon Mattes的回答的启发,我需要满足IHttpActionResult要求的ResponseMessageResult的返回类型。同样使用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))
});
参见nashawn对JsonContent的回答。
毫无疑问你是对的,弗罗林。我在做这个项目时,发现了这样一段代码:
product = await response.Content.ReadAsAsync<Product>();
可替换为:
response.Content = new StringContent(string product);