ASP.NET MVC Controller extensions
In the course of preparing a soon-to-come showcase on ASP.NET MVC I needed to redirect a controller method to another controller's. I found this post by Matt hawley that got me started but I had to fix a bug. Since I had already created my own extension methods to allow sending a file as attachment, I took the liberty of repackaging Matt's code and mine into a single class.
Zipped source code is here : MvcControllerExtensions.zip
So what's in it ?
A. Changes from Matt's code :
I changed all RedirectToAction<T>(this T controller, ... to RedirectToAction<T>(this Controller controller, ... so that the target controller (T) does not have to be the invoking controller (this).
I also moved the class to System.Web.Mvc so that it doesn't require additional usings. It's enough that you include the code in your project.
B. My extension methods :
I first created a DelegatedActionResult which allows Controller methods to delegate execution of the action, like so :
return new DelegatedActionResult(c => c.HtppContext.response.Close());
Then I used this to extend the Controller class with a new method SendFileAsAttachment, which comes in two flavours : you can either provide a filename or a delegate that get called to write into the http response stream.
public ActionResult GetLogo(string companyName)
{
return this.SendFileAsAttachment(Server.MapPath("~/App_Data/Logos/" + companyName + ".jpg"));
}
or
public ActionResult GetFile(int fileId)
{
var database = DataProvider.GetFileManager();
return this.SendFileAsAttachment(database.GetFilename(fileId),
(fileId, outputStream) =>
database.LoadFile(fileId, outputStream));
}