pra*_*tor 167 c# asp.net-mvc asp.net-web-api
几个月前,微软决定更改HttpResponseMessage类.之前,您可以简单地将数据类型传递给构造函数,然后返回包含该数据的消息,但不再是.
现在,您需要使用Content属性来设置消息的内容.问题是它是HttpContent类型,我似乎无法找到将字符串转换为HttpContent的方法.
有谁知道如何处理这个问题?非常感谢.
Jim*_*eil 199
具体来说,对于字符串,最快的方法是使用StringContent构造函数
response.Content = new StringContent("Your response text");
Run Code Online (Sandbox Code Playgroud)
对于其他常见场景,还有许多其他HttpContent类后代.
Flo*_*scu 123
您应该使用Request.CreateResponse创建响应:
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error message");
Run Code Online (Sandbox Code Playgroud)
您可以将对象而不仅仅是字符串传递给CreateResponse,它将根据请求的Accept标头对它们进行序列化.这使您无需手动选择格式化程序.
pra*_*tor 58
显然,新的方法在这里详细说明:
http://aspnetwebstack.codeplex.com/discussions/350492
引用亨里克,
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new ObjectContent<T>(T, myFormatter, "application/some-format");
Run Code Online (Sandbox Code Playgroud)
所以基本上,必须创建一个ObjectContent类型,它显然可以作为HttpContent对象返回.
Sim*_*tes 45
最简单的单线解决方案就是使用
return new HttpResponseMessage( HttpStatusCode.OK ) {Content = new StringContent( "Your message here" ) };
Run Code Online (Sandbox Code Playgroud)
对于序列化的JSON内容:
return new HttpResponseMessage( HttpStatusCode.OK ) {Content = new StringContent( SerializedString, System.Text.Encoding.UTF8, "application/json" ) };
Run Code Online (Sandbox Code Playgroud)
Scu*_*eve 39
对于任何T对象,您可以:
return Request.CreateResponse<T>(HttpStatusCode.OK, Tobject);
Run Code Online (Sandbox Code Playgroud)
byt*_*dev 15
您可以创建自己的专用内容类型.例如,一个用于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")
{
}
}
Run Code Online (Sandbox Code Playgroud)
受 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))
});
Run Code Online (Sandbox Code Playgroud)
请参阅 nashawn 对 JsonContent 的回答。
归档时间: |
|
查看次数: |
217184 次 |
最近记录: |