locked
How to return customer data with HttpResponseMessage RRS feed

  • Question

  • User264732274 posted
                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 ?

    thanks

    Monday, August 29, 2016 11:41 AM

Answers

  • User36583972 posted

    Hi sudip_inn,

    You can try the following code.

    Web API:

       [AllowAnonymous]
            public HttpResponseMessage Post()
            {
                JoinGroupItem msg = new JoinGroupItem() { id="001", Age=26 };
                HttpResponseMessage response = new HttpResponseMessage();
                response.StatusCode = HttpStatusCode.OK;
                response.ReasonPhrase = "SUCCESS";
                response.Content = new ObjectContent<JoinGroupItem>(msg, new JsonMediaTypeFormatter(), "application/json");
                return response;
            }

    Client:

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullPath);//
                request.Method = "Post";
                request.KeepAlive = true;
                request.ContentLength = 0;
                request.ContentType = "text/json";
                request.Accept = "application/json"; 
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string myResponse = "";
                using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    myResponse = sr.ReadToEnd().ToString();
                }
                Response.Write(myResponse);

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 30, 2016 1:39 AM