ASP.NET MVC 控制器可以返回图像吗? [英] Can an ASP.NET MVC controller return an Image?
问题描述
我可以创建一个只返回图像资产的控制器吗?
Can I create a Controller that simply returns an image asset?
每当请求如下 URL 时,我想通过控制器路由此逻辑:
I would like to route this logic through a controller, whenever a URL such as the following is requested:
www.mywebsite.com/resource/image/topbanner
控制器将查找 topbanner.png
并将该图像直接发送回客户端.
The controller will look up topbanner.png
and send that image directly back to the client.
我见过这样的例子,你必须创建一个视图 - 我不想使用视图.我只想用控制器来完成这一切.
I've seen examples of this where you have to create a View - I don't want to use a View. I want to do it all with just the Controller.
这可能吗?
推荐答案
使用基本控制器 File 方法.
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");
}
请注意,这似乎相当有效.我做了一个测试,我通过控制器(http://localhost/MyController/Image/MyImage
)和直接 URL(http://localhost/Images/MyImage.jpg
),结果是:
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 毫秒
- 直接:每张照片 6.7 毫秒
- 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.
这篇关于ASP.NET MVC 控制器可以返回图像吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!