Adsence750x90

Sunday, July 27, 2014

How to return JSON from WebAPI 2

Nowadays JSON is more common than XML, Most of the JavaScript frameworks work well with JSON contents, AngularJS is an excellent example. Default WebAPI have   IEnumerable<string>  Get() and string Get(int id) methods

Take a look
public class DefaultController : ApiController
    {
        // GET api/default2
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/default2/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/default2
        public void Post([FromBody]string value)
        {
        }

        // PUT api/default2/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/default2/5
        public void Delete(int id)
        {
        }
    }

If you wish to return a JSON instead of string from WebAPI 2 may face some issues, So How can it resolved? You can return HttpResponseMessage instead of string or IEnumerable.. If you want to read more check this out Two ways to work with HTTP responses in ApiController Below code will return JSON string for you

       [Route("api/Default/GetProductLookup/{id}")]
        public HttpResponseMessage GetProductLookup(string id)
        {
            string json = "Your JSON String";
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return response;
        }

Here is the whole class
public class DefaultController : ApiController
    {
        // GET api/default2
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/default2/5
        public string Get(int id)
        {
            return "value";
        }

        [Route("api/Default/GetProductLookup/{id}")]
        public HttpResponseMessage GetProductLookup(string id)
        {
            string json = "Your JSON String";
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return response;
        }

        // POST api/default2
        public void Post([FromBody]string value)
        {
        }

        // PUT api/default2/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/default2/5
        public void Delete(int id)
        {
        }
    }

No comments: