1

Controller:

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");

}

Generated HTML:

<img style="-webkit-user-select: none" src="http://localhost:38315/Beacon/999">

However the image is not displayed. In Chrome it's a small box with grey borders and in MS Edge there is a box with an "X" in it which I assume is the "File not found" image.

I have tried returning different images (to make sure the first one was not corrupt), several Content Types but without any luck.

I'm sure that the different files that I have tried with exists.

I read this post: ASP.Net MVC - Img Src Server Path

I have tried this:

return File("~/images/beacon.png", "image/png");

I have tried returning a Base64 string but with no luck.

When I run this code it states that the file do exist:

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");

How can I return a simple image through a Controller?

* Willy David Jr Suggestion *

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

Community
  • 1
  • 1
Westerlund.io
  • 2,743
  • 5
  • 30
  • 37
  • 1
    Does it hit the action when debugging? Check that the path given to the image is maps to an action. Also, do a `System.IO.File.Exsits(path)` on the path and make sure that the derived path is there. Chances are that you are generating the path wrong. – Nkosi Jan 25 '17 at 00:43
  • @Nkosi Updated answer. "res" is true i.e. it seems to exist. – Westerlund.io Jan 25 '17 at 00:47

2 Answers2

1

Try the following and see if it applies to your situation.

public ActionResult Beacon(string value) {
    var dir = Server.MapPath("/Content/Images/Sprites/");
    var path = Path.Combine(dir, "logo.png");
    var theFile = new FileInfo(path);
    if (theFile.Exists) {
        return File(System.IO.File.ReadAllBytes(path), "image/png");
    }
    return this.HttpNotFound();                
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
0

Try to do this:

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();                
}
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57