2023-02-17 420
我可以创建一个简单地返回图像资产的控制器吗?
我想通过控制器将此逻辑路由,每当请求如下所示的URL时:
www.mywebsite.com/resource/image/topbanner
控制器将查找topbanner.png并将该图像直接发送回客户端.
我已经看到了它的例子,其中您必须创建一个视图 – 我不想使用视图.我想用控制器做一切.
这是可能的吗?
使用基本控制器文件方法.
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)并通过直接网址(http://localhost/Images/MyImage.jpg),结果是:
注意:这是请求的平均时间.通过在本地机器上制作数千个请求来计算平均值,因此总计不应包括网络延迟或带宽问题.
使用mvc的发布版本,这是我做的:
[AcceptVerbs(HttpVerbs.Get)]
[OutputCache(CacheProfile = "CustomerImages")]
public FileResult Show(int customerId, string imageName)
{
var path = string.Concat(ConfigData.ImagesDirectory, customerId, "\\", imageName);
return new FileStreamResult(new FileStream(path, FileMode.Open), "image/jpeg");
}
我显然在这里有一些应用程序特定的东西关于路径建设,但FiltereamResult的返回很好,简单.
我对这种动作进行了一些性能测试,对您的日常调用对图像(绕过控制器),平均值的差异仅为3毫秒(控制器AVG为68ms,非控制器为65ms).
我已经尝试了一些答案中提到的其他方法,并且性能命中更加戏剧性……一些解决方案响应与非控制器(其他控制器AVG 340ms,非控制器65ms)一样多. ).
略微阐述Dyland的响应:
三个类实现 fileresult 类:
System.Web.Mvc.FileResult
System.Web.Mvc.FileContentResult
System.Web.Mvc.FilePathResult
System.Web.Mvc.FileStreamResult
他们都是自我解释的:
下面是使用内容处理技术(未测试)的示例:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetFile()
{
// No need to dispose the stream, MVC does it for you
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "myimage.png");
FileStream stream = new FileStream(path, FileMode.Open);
FileStreamResult result = new FileStreamResult(stream, "image/png");
result.FileDownloadName = "image.png";
return result;
}
以上所述是小编给大家介绍的ASP.NET MVC控制器可以返回一个图像吗?,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!
原文链接:https://77isp.com/post/34175.html
=========================================
https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。
数据库技术 2022-03-28
网站技术 2022-11-26
网站技术 2023-01-07
网站技术 2022-11-17
Windows相关 2022-02-23
网站技术 2023-01-14
Windows相关 2022-02-16
Windows相关 2022-02-16
Linux相关 2022-02-27
数据库技术 2022-02-20
抠敌 2023年10月23日
嚼餐 2023年10月23日
男忌 2023年10月22日
瓮仆 2023年10月22日
簿偌 2023年10月22日
扫码二维码
获取最新动态