A day with .Net

My day to day experince in .net

Return Json from a Web Api via HttpResponseMessage

Posted by vivekcek on June 26, 2016

This is a small tip to send json data through HttpResponseMessage.

First create the helper class in your Web Api Controller.

public class JsonContent : HttpContent
    {

        private readonly MemoryStream _Stream = new MemoryStream();
        public JsonContent(object value)
        {

            Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var jw = new JsonTextWriter(new StreamWriter(_Stream));
            jw.Formatting = Formatting.Indented;
            var serializer = new JsonSerializer();
            serializer.Serialize(jw, value);
            jw.Flush();
            _Stream.Position = 0;

        }
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            return _Stream.CopyToAsync(stream);
        }

        protected override bool TryComputeLength(out long length)
        {
            length = _Stream.Length;
            return true;
        }
    }

Now try this in your Action method.

public HttpResponseMessage Delete(int id)
        {
            return new HttpResponseMessage()
            {
                Content = new JsonContent(new
                {
                    Name = "Vivek",
                    Address = "Address",
                    Message = "Any Message" //return exception
                })
            };
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s