Mathias Lykkegaard Lorenzen Mathias Lykkegaard Lorenzen - 3 months ago 10
C# Question

ASP .NET MVC - Have a controller method that returns an image in the response?

How can I make a controller method called

GetMyImage()
which returns an image as the response (that is, the content of the image itself)?

I thought of changing the return type from
ActionResult
to
string
, but that doesn't seem to work as expected.

Answer

Return FilePathResult using File method of controller

public ActionResult GetMyImage(string ImageID)
{
    // Construct absolute image path
    var imagePath = "whatever";

    return base.File(imagePath, "image/jpg");
}

There are several overloads of File method. Use whatever is most appropriate for your situation. For example if you wanted to send Content-Disposition header so that the user gets the SaveAs dialog instead of seeing the image in the browser you would pass in the third parameter string fileDownloadName.

Comments