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?
HttpResponseMessage. If the action returns an HttpResponseMessage, Web API converts the return value directly into an HTTP response message, using the properties of the HttpResponseMessage object to populate the response. This option gives you a lot of control over the response message.
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.
Helper method that performs content negotiation and creates a HttpResponseMessage with an instance of System.Net.Http.ObjectContent`1 as the content and OK as the status code if a formatter can be found. If no formatter is found, this method returns a response with status 406 NotAcceptable.
HttpResponseMessage In WebAPI. HttpResponseMessage A HttpResponseMessage allows us to work with the HTTP protocol (for example, with the headers property) and unifies our return type. In simple words an HttpResponseMessage is a way of returning a message/data from your action. The following is a quick glimpse of that:
In simple words an HttpResponseMessage is a way of returning a message/data from your action. Since we can return primitive types or complex types to the user, why HttpResponseMessage? Let's create a simple get method that will return the Employee data for the id provided.
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.
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.
Request.CreateResponse(...) is just a builder, it also returns instance of HttpResponseMessage, here is the code:
public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value, HttpConfiguration configuration)
{
if (request == null)
throw Error.ArgumentNull("request");
configuration = configuration ?? HttpRequestMessageExtensions.GetConfiguration(request);
if (configuration == null)
throw Error.InvalidOperation(SRResources.HttpRequestMessageExtensions_NoConfiguration, new object[0]);
IContentNegotiator contentNegotiator = ServicesExtensions.GetContentNegotiator(configuration.Services);
if (contentNegotiator == null)
{
throw Error.InvalidOperation(SRResources.HttpRequestMessageExtensions_NoContentNegotiator, new object[1]
{
(object) typeof (IContentNegotiator).FullName
});
}
else
{
IEnumerable<MediaTypeFormatter> formatters = (IEnumerable<MediaTypeFormatter>) configuration.Formatters;
ContentNegotiationResult negotiationResult = contentNegotiator.Negotiate(typeof (T), request, formatters);
if (negotiationResult == null)
{
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.NotAcceptable,
RequestMessage = request
};
}
else
{
MediaTypeHeaderValue mediaType = negotiationResult.MediaType;
return new HttpResponseMessage()
{
Content = (HttpContent) new ObjectContent<T>(value, negotiationResult.Formatter, mediaType),
StatusCode = statusCode,
RequestMessage = request
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With