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 }) }; }
Related
This entry was posted on June 26, 2016 at 7:34 am and is filed under MVC, Web API. Tagged: Json HttpResponseMessage, Json Web Api HttpResponseMessage, Return Json from a Web Api via HttpResponseMessage. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Tony Paille said
Thanks – just what I was looking for.