Can I create a Controller that simply returns an image asset?
I would like to route this logic through a controller, whenever a URL such as the following is requeste
To expland on Dyland's response slightly:
Three classes implement the FileResult class:
System.Web.Mvc.FileResult
System.Web.Mvc.FileContentResult
System.Web.Mvc.FilePathResult
System.Web.Mvc.FileStreamResult
They're all fairly self explanatory:
FilePathResult
- this is the easiest way and avoids you having to use Streams.FileContentResult
.FileStreamResult
in a similar way to below, but with a MemoryStream
and using GetBuffer()
.Streams
use FileStreamResult
. It's called a FileStreamResult but it takes a Stream
so I'd guess it works with a MemoryStream
.Below is an example of using the content-disposition technique (not tested):
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetFile()
{
// No need to dispose the stream, MVC does it for you
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "myimage.png");
FileStream stream = new FileStream(path, FileMode.Open);
FileStreamResult result = new FileStreamResult(stream, "image/png");
result.FileDownloadName = "image.png";
return result;
}