How can I return Images from Web API in ASP.NET?


Hello,

I haven't used much of the Web API as of now, so I was thinking how can I return Web API from API controller in ASP.NET?

Any Code sample, links?

Thanks


Asked by:- neena
1
: 153 At:- 4/11/2018 8:57:34 AM
C# Web API return image from web api in asp.net






1 Answers
profileImage Answered by:- Vinnu

You can return Image from ASP.NET Web API using HttpResponseMessage in C# APIController, something like below example:

    public HttpResponseMessage GetImage(int id)
    {
      ImageDbContext db = new ImageDbContext();

      var data = from i in db.Images
                 where i.Id == id
                 select i;

      Image img = (Image)data.SingleOrDefault();

      byte[] imgData = img.ImageData;

      MemoryStream ms = new MemoryStream(imgData);

      HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

      response.Content = new StreamContent(ms);

      response.Content.Headers.ContentType = new 
      System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
       //send response of image/png type
      return response;
    }

In the above method,  return type of GetImage() method is HttpResponseMessage. The HttpResponseMessage class from System.Net.Http represents an HTTP response that includes the HTTP status code and the response data. The GetImage() method accepts an Image id that is to be retrieved. Inside, it fetches the Image from the database and puts the ImageData in a byte array. A new MemoryStream is then created based on this byte array.

3
At:- 4/13/2018 11:08:54 AM
Thanks 0
By : neena - at :- 4/22/2018 12:21:32 PM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use