【发布时间】:2017-01-27 08:31:31
【问题描述】:
控制器:
public ActionResult Beacon(string value)
{
var dir = Server.MapPath("/Content/Images/Sprites/");
var path = Path.Combine(dir, "logo.png");
return base.File(path, "image/png");
}
生成的 HTML:
<img style="-webkit-user-select: none" src="http://localhost:38315/Beacon/999">
但是图像不显示。在 Chrome 中,它是一个带有灰色边框的小框,在 MS Edge 中,有一个带有“X”的框,我认为它是“找不到文件”图像。
我尝试返回不同的图像(以确保第一个没有损坏),几种内容类型但没有任何运气。
我确定我尝试过的不同文件存在。
我读了这篇文章:ASP.Net MVC - Img Src Server Path
我试过这个:
return File("~/images/beacon.png", "image/png");
我尝试返回 Base64 字符串,但没有成功。
当我运行此代码时,它表明该文件确实存在:
var dir = Server.MapPath("/images");
var path = Path.Combine(dir, "beacon.png");
var res = System.IO.File.Exists(path);
return base.File(path, "image/png");
如何通过控制器返回简单的图像?
* Willy David Jr 建议 *
public ActionResult Beacon(string value) {
var path = Server.MapPath(Url.Content("~/Content/Images/Sprites/")) + "logo.png";
var theFile = new FileInfo(path);
if (theFile.Exists) {
return File(System.IO.File.ReadAllBytes(path), "image/png");
//or return base.File(path, "image/png");
}
return this.HttpNotFound();
}
【问题讨论】:
-
调试时是否命中动作?检查给定图像的路径是否映射到动作。另外,在路径上执行
System.IO.File.Exsits(path)并确保派生路径在那里。您生成的路径可能是错误的。 -
@Nkosi 更新了答案。 “res”是真的,即它似乎存在。
标签: c# asp.net-mvc-4