Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

output image using web api HttpResponseMessage

I'm trying the following code to output a image from a asp.net web api, but the response body length is always 0.

public HttpResponseMessage GetImage() {     HttpResponseMessage response = new HttpResponseMessage();     response.Content = new StreamContent(new FileStream(@"path to image"));     response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");      return response; } 

Any tips?

WORKS:

    [HttpGet]     public HttpResponseMessage Resize(string source, int width, int height)     {         HttpResponseMessage httpResponseMessage = new HttpResponseMessage();          // Photo.Resize is a static method to resize the image         Image image = Photo.Resize(Image.FromFile(@"d:\path\" + source), width, height);          MemoryStream memoryStream = new MemoryStream();          image.Save(memoryStream, ImageFormat.Jpeg);          httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray());          httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");         httpResponseMessage.StatusCode = HttpStatusCode.OK;          return httpResponseMessage;     } 
like image 994
lolol Avatar asked Oct 21 '12 19:10

lolol


People also ask

How can I return images from Web API in asp net?

In order to return images stored directly in a SQL Server database from an ASP.NET Web API you need to create a Get() method that returns HttpResponseMessage. The Content property of the HttpResponseMessage class represents the binary image data associated with an image.

How do I return an image in .NET core API?

In . NET Core, you don't need to create " HttpResponseMessage " to return images from API, it will not return you data, also it will not throw any error, you have to use File() method directly inside the Controller. Basically, the API will accept a query string which is the file name.

What is HttpResponseMessage in Web API?

HttpResponseMessage. If the action returns an HttpResponseMessage, Web API converts the return value directly into an HTTP response message, using the properties of the HttpResponseMessage object to populate the response. This option gives you a lot of control over the response message.


1 Answers

The the following:

  1. Ensure path is correct (duh)

  2. Ensure your routing is correct. Either your Controller is ImageController or you have defined a custom route to support "GetImage" on some other controller. (You should get a 404 response for this.)

  3. Ensure you open the stream:

    var stream = new FileStream(path, FileMode.Open);

I tried something similar and it works for me.

like image 111
Daniel Miller Avatar answered Sep 22 '22 08:09

Daniel Miller