Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

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.

like image 386
Mathias Lykkegaard Lorenzen Avatar asked Feb 13 '12 18:02

Mathias Lykkegaard Lorenzen


People also ask

How does controller work in MVC?

A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.

What is the return type of action result in MVC?

Action Result is actually a data type. When it is used with action method, it is called return type. As you know, an action is referred to as a method of the controller, the Action Result is the result of action when it executes. In fact, Action Result is a return type.

How does request and response work in MVC?

Handlers are responsible for generating the actual response in MVC. They implement the IHttpHandler class and only one handler will execute per request. On the other hand, HttpModules are created in response to life cycle events. Modules can, for example, be used for populating HttpContext objects.

Can a Web API controller return an MVC view?

Solution 1You don't. You can return one or the other, not both. Frankly, a WebAPI controller returns nothing but data, never a view page. A MVC controller returns view pages.


1 Answers

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.

like image 58
amit_g Avatar answered Sep 19 '22 01:09

amit_g