Can an ASP.NET MVC controller return an Image?

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

    You can write directly to the response but then it isn't testable. It is preferred to return an ActionResult that has deferred execution. Here is my resusable StreamResult:

    public class StreamResult : ViewResult
    {
        public Stream Stream { get; set; }
        public string ContentType { get; set; }
        public string ETag { get; set; }
    
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = ContentType;
            if (ETag != null) context.HttpContext.Response.AddHeader("ETag", ETag);
            const int size = 4096;
            byte[] bytes = new byte[size];
            int numBytes;
            while ((numBytes = Stream.Read(bytes, 0, size)) > 0)
                context.HttpContext.Response.OutputStream.Write(bytes, 0, numBytes);
        }
    }
    

提交回复
热议问题