Image File as Response from .NET Web API

When developing a web API, it is often required to send response as a PDF or image file.
Following lines of code will assist to create method that will override the default media type of the response determined by Content Negotiation.

public HttpResponseMessage GetImage()
        {
            byte[] bytes = System.IO.File.ReadAllBytes(
            HttpContext.Current.Server
            .MapPath(“~/Content/myImage.png”));
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(bytes);
            result.Content.Headers.ContentType
            = new MediaTypeHeaderValue(“image/png”);
            return result;
        }

The key to this implementation is the use of the HttpResponseMessage class, which
helps to create a raw HTTP response in the controller itself.

We then set the HTTP 200 status code using the enum HttpStatusCode.OK and set the image bytes as response content.

The last step is to set the media type header to image/png, and the response is returned as HttpResponseMessage type.

Reference:
Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API

Tags: