Put content in HttpResponseMessage object?

praetor picture praetor · Sep 3, 2012 · Viewed 251.4k times · Source

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.

Answer

Jim O'Neil picture Jim O'Neil · Sep 3, 2012

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.