Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 263
user197508 Avatar asked Feb 27 '14 06:02

user197508


People also ask

What is the use of HttpResponseMessage?

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.

How do I pass content in HttpResponseMessage?

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.

What is helper method in httpresponsemessage?

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.

What is httpresponsemessage in WebAPI?

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:

What is httpresponsemessage in Laravel?

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.

How to override conneg results in httpresponsemessage?

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.


2 Answers

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.

like image 84
Badri Avatar answered Oct 07 '22 05:10

Badri


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
      };
    }
  }
like image 20
Anton Levshunov Avatar answered Oct 07 '22 03:10

Anton Levshunov