Can an ASP.NET MVC controller return an Image?

前端 未结 19 1669
旧时难觅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:34

    You can create your own extension and do this way.

    public static class ImageResultHelper
    {
        public static string Image(this HtmlHelper helper, Expression> action, int width, int height)
                where T : Controller
        {
            return ImageResultHelper.Image(helper, action, width, height, "");
        }
    
        public static string Image(this HtmlHelper helper, Expression> action, int width, int height, string alt)
                where T : Controller
        {
            var expression = action.Body as MethodCallExpression;
            string actionMethodName = string.Empty;
            if (expression != null)
            {
                actionMethodName = expression.Method.Name;
            }
            string url = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection).Action(actionMethodName, typeof(T).Name.Remove(typeof(T).Name.IndexOf("Controller"))).ToString();         
            //string url = LinkBuilder.BuildUrlFromExpression(helper.ViewContext.RequestContext, helper.RouteCollection, action);
            return string.Format("\"{3}\"", url, width, height, alt);
        }
    }
    
    public class ImageResult : ActionResult
    {
        public ImageResult() { }
    
        public Image Image { get; set; }
        public ImageFormat ImageFormat { get; set; }
    
        public override void ExecuteResult(ControllerContext context)
        {
            // verify properties 
            if (Image == null)
            {
                throw new ArgumentNullException("Image");
            }
            if (ImageFormat == null)
            {
                throw new ArgumentNullException("ImageFormat");
            }
    
            // output 
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.ContentType = GetMimeType(ImageFormat);
            Image.Save(context.HttpContext.Response.OutputStream, ImageFormat);
        }
    
        private static string GetMimeType(ImageFormat imageFormat)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            return codecs.First(codec => codec.FormatID == imageFormat.Guid).MimeType;
        }
    }
    public ActionResult Index()
        {
      return new ImageResult { Image = image, ImageFormat = ImageFormat.Jpeg };
        }
        <%=Html.Image(c => c.Index(), 120, 30, "Current time")%>
    

提交回复
热议问题