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; }
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.
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.
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.
The the following:
Ensure path is correct (duh)
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.)
Ensure you open the stream:
var stream = new FileStream(path, FileMode.Open);
I tried something similar and it works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With