简体   繁体   中英

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 ?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM