1

I am trying to display images from the local storage(not Content folder). The image tag I am using looks like this.

@if (Model.PreviousCoverPic != null)
{
    <img src="@Url.Action("ServeImage", "Profile",new {path = Model.PreviousCoverPic})" alt="Previous Profile Pic" />
}

I made the ServerImage method an extension method since it will be used by more than one controller. Here is the code for the method:

public static ActionResult ServeImage(this System.Web.Mvc.Controller controller, string path)
{
    Stream stream = new FileStream(path, FileMode.Open);
    FileResult fileResult = new FileStreamResult(stream, "image/jpg");
    return fileResult;
}

It returns a FileResult of the image so that it can be displayed. However, when the view is rendered it doesn't show the image. I checked the Model.PreviousCoverPic value and it is not null. What am I missing here? How can I achieve displaying methods from a local folder? Also, I followed the answer in this question and added the name space of the class which contains the extension method but the image still doesn't get rendered in the view.

Community
  • 1
  • 1
xabush
  • 849
  • 1
  • 13
  • 29

1 Answers1

2

According to the following sources

Can MVC action method be static or extension method

And this answer

extend ASP.NET MVC action method,How to do return View

The extension method wont work with routing the Url.Action. You can use inheritance to make a base class with the action. that way all inherited classes will have the action and calls to Url.Action will be valid.

public abstract class MyBaseController : Controller {
    public ActionResult ServeImage(string path) {...}
}

public class ConcreteController : MyBaseController {...}
Community
  • 1
  • 1
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Thanks, I works that way. I thought using extension methods would be cleaner. Is there a way to make it work using extension methods? – xabush Mar 09 '16 at 12:51
  • I can't think of anything at the moment and haven't come across any documentation about being able to do that as yet. – Nkosi Mar 09 '16 at 12:56
  • You're right. Action methods cannot be used as extension methods. Take a look at [this](http://stackoverflow.com/questions/32514087/extend-asp-net-mvc-action-method-how-to-do-return-view) question. Please modify your answer to include that information. Also can I return more than one content type, like "image/jpg", "image/png", and so on. – xabush Mar 09 '16 at 13:31
  • The header will only include one type at a time. I would suggest mapping the file to its mime type and including that in the stream result. But that a whole other question. There are answers to that on SO. – Nkosi Mar 09 '16 at 13:35