问题描述
我可以创建一个控制器,仅仅返回一个图像资产?
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");
return base.File(path, "image/jpeg");
}
作为一个说明,这似乎是相当有效的。我做了一个测试,我请求的图像通过控制器(的http://本地主机/ myController的/图像/ 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控制器可以返回一个图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!