Monojit Sarkar Monojit Sarkar - 3 months ago 10
C# Question

How to return customer data with HttpResponseMessage

HttpResponseMessage r = new HttpResponseMessage();
r.StatusCode = HttpStatusCode.OK;
r.ReasonPhrase = "SUCCESS";


now how could i pass my customer object by
HttpResponseMessage
class to client side ?

one way is
return Request.CreateResponse(HttpStatusCode.OK, customers);


suppose if i do not want to return response this way
Request.CreateResponse(HttpStatusCode.OK, customers);
rather i want to create instance of
HttpResponseMessage
and initialize few property and then return. so tell me ow could i pass my customer object by
HttpResponseMessage class
to client side ?

Answer

The simple way is you should create response based on the request:

return Request.CreateResponse(HttpStatusCode.OK, customers);

Because under the hood, this method will deal the content negotiation for you which you don't care much. Otherwise, you have to deal manually as below code:

IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();

ContentNegotiationResult result = negotiator.Negotiate(
    typeof(Customer), this.Request, this.Configuration.Formatters);

var response = new HttpResponseMessage
{
    StatusCode = HttpStatusCode.OK,
    Content = new ObjectContent<Customer>(customer,
        result.Formatter, result.MediaType)
};

return response;
Comments