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
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.
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.
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);
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.
Inspired by Simon Mattes' answer, I needed to satisfy IHttpActionResult required return type of ResponseMessageResult. Also using nashawn's JsonContent, I ended up with...
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.
The easiest single-line solution is to use
return new HttpResponseMessage( HttpStatusCode.OK ) {Content = new StringContent( "Your message here" ) };
For serialized JSON content:
return new HttpResponseMessage( HttpStatusCode.OK ) {Content = new StringContent( SerializedString, System.Text.Encoding.UTF8, "application/json" ) };