Put content in HttpResponseMessage object?
Several months ago, Microsoft decided to change up the HttpResponseMessage class. 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. 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.
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
response.Content = new StringContent("Your response text");
There are a number of additional HttpContent class descendants for other common scenarios.
You should create the response using 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. This saves you from manually choosing a formatter.
Apparently the new way to do it is detailed here:
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.
链接地址: http://www.djcxy.com/p/20422.html