Search code examples
c#asp.net-mvcasp.net-web-api

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?


Solution

  • Apparently the new way to do it is detailed in this (archived) CodePlex discussion post by Microsoft developer Henrik Nielson:

    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.