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
Solution 1: To render an image in a view from an image URL
You can create your own extension method:
public static MvcHtmlString Image(this HtmlHelper helper,string imageUrl)
{
string tag = "";
tag = string.Format(tag,imageUrl);
return MvcHtmlString.Create(tag);
}
Then use it like:
@Html.Image(@Model.ImagePath);
Solution 2: To render image from database
Create a controller method that returns image data like below
public sealed class ImageController : Controller
{
public ActionResult View(string id)
{
var image = _images.LoadImage(id); //Pull image from the database.
if (image == null)
return HttpNotFound();
return File(image.Data, image.Mime);
}
}
And use it in a view like:
@ { Html.RenderAction("View","Image",new {id=@Model.ImageId})}
To use an image rendered from this actionresult in any HTML, use