Can an ASP.NET MVC controller return an Image?

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

    Use the base controllers File method.

    public ActionResult Image(string id)
    {
        var dir = Server.MapPath("/Images");
        var path = Path.Combine(dir, id + ".jpg"); //validate the path for security or use other means to generate the path.
        return base.File(path, "image/jpeg");
    }
    

    As a note, this seems to be fairly efficient. I did a test where I requested the image through the controller (http://localhost/MyController/Image/MyImage) and through the direct URL (http://localhost/Images/MyImage.jpg) and the results were:

    • MVC: 7.6 milliseconds per photo
    • Direct: 6.7 milliseconds per photo

    Note: this is the average time of a request. The average was calculated by making thousands of requests on the local machine, so the totals should not include network latency or bandwidth issues.

提交回复
热议问题