user197508 user197508 - 1 year ago 120
C# Question

When to use HttpResponseMessage and Request.CreateResponse

When should we use the

HttpResponseMessage
object and when should we use the
Request.CreateResponse(...)
method?

Also, what is the difference between the
HttpResponseMessage
object and the
Request.CreateResponse(...)
method?

Answer Source

What is difference between HttpResponseMessage object and Request.CreateResponse(...) method?

It is probably obvious but Request.CreateResponse is a helper method for creating HttpResponseMessage object.

When we must use HttpResponseMessage object and When we must use Request.CreateResponse(...) method?

If you want to use the built-in content negotiation feature, use Request.CreateResponse. When you return an object, ASP.NET Web API has to serialize the object into response body. This could be generally JSON or XML (other media types are possible but you need to create the formatter). The media type chosen (JSON or XML) is based on the request content type, Accept header in the request and so on and content negotiation is the process that determines the media type to be used. By using Request.CreateResponse, you are automatically using the result of this process.

On the other hand, if you create HttpResponseMessage yourself, you have to specify a media formatter based on which the object will be serialized and by specifying the media formatter yourself, you can override the results of conneg.

EDIT Here is an example of how to specify JSON formatter.

public HttpResponseMessage Get(int id)
{
    var foo = new Foo() { Id = id };
    return new HttpResponseMessage()
    {
        Content = new ObjectContent<Foo>(foo,
                  Configuration.Formatters.JsonFormatter)
    };
}

With this, even if you send a request with Accept:application/xml, you will only get JSON.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download