一个ASP.NET MVC控制器可以返回一个图像?
我可以创建一个简单地返回图片资源的控制器吗?
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.
这是可能吗?
使用基本控制器文件方法。
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:
- 每张照片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.