Can an ASP.NET MVC controller return an Image?

前端 未结 19 1633
旧时难觅i
旧时难觅i 2020-11-22 02:10

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

19条回答
  •  你的背包
    2020-11-22 02:30

    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

    
                                                            
提交回复
热议问题