从Controller返回图像

时间:2017-01-25 00:13:10

标签: c# asp.net-mvc-4

控制器:

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();                
}

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

请尝试以下操作,看看它是否适用于您的情况。

<rewrite>
   <rules>
      <rule name="Redirect domain" enabled="true">
         <match url="^(.*)$" />
         <conditions>
            <add input="{HTTP_HOST}" pattern="^(www\.)?example2\.com$" />
         </conditions>
         <action type="Rewrite" url="folder/{R:1}" />
      </rule>
   </rules>
</rewrite>

答案 1 :(得分:0)

尝试这样做:

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();                
}