2

I have a requirement to return an image from a WebApi using IHttpActionResult instead of HttpResponseMessage. How this can be achieved & what are the accept & content type headers need to be passed?

Thanks!!

Angular-User
  • 151
  • 1
  • 3
  • 7

2 Answers2

2

I was actually looking for a solution to send an image resides on internet from web api but I am returning local thumbnail images from my web api with the following code;

[HttpGet]
[Route("thumbnail/{userId}/{fileName}")]
public IHttpActionResult GetThumbnail()
{
        var mediaRoot = System.Web.HttpContext.Current.Server.MapPath("~/media");

        var imgPath = Path.Combine(mediaRoot, "images", userId, "thumbnail", fileName);
        var fileInfo = new FileInfo(imgPath);

        return !fileInfo.Exists
            ? (IHttpActionResult)NotFound()
            : new FileResult(fileInfo.FullName);
}

Hope this helps

Edit: You should create a custom IHttpActionResult to retun images,

It seems i have created a custom IHttpActionResult to return images and here is the post that i got this code from > Custom IHttpActionResult

Community
  • 1
  • 1
Azadrum
  • 756
  • 6
  • 23
0

This would be a basic way:

[HttpGet]
[Route("test")]
public IHttpActionResult GetImageTest()
{
    var stream = File.OpenRead(@"C:\picture.jpg");

    var response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);

    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
    response.Content.Headers.ContentLength = stream.Length;

    return ResponseMessage(response);
}
Vic_HT
  • 411
  • 5
  • 5