Rafael
Rafael

Reputation: 1223

Display image from file path asp.net mvc4

I'm trying to display an image outside of the root folder of my asp .net mvc4 project - to no avail. The img tag I have tried inside the .master page and .ascx control is:

<img src='@Url.Action("someimage", "imagesController")' />

My controller looks like:

class imagesController : Controller
{
    public ActionResult someimage()
    {
        return File(@"C:\...\image.png", "image/png");
    }
}

The method above doesn't get called, instead I'm getting a: http://localhost:62372/Builder/@Url.Action(%22someimage%22,%20%22imagesController%22) Failed to load resource: the server responded with a status of 500 (Internal Server Error)

This is my routing, in case it matters:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

        //--default routing and default route--
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Login", action = "OpenLogin", id = UrlParameter.Optional } // Parameter defaults
        );

    }

I have gathered more info about the error: Exception information:

Exception type: ArgumentException

Exception message: Illegal characters in path.

at System.IO.Path.CheckInvalidPathChars(String path)

at System.IO.Path.Combine(String path1, String path2)

...

Upvotes: 1

Views: 1758

Answers (2)

Rafael
Rafael

Reputation: 1223

In the end I got it working by using this syntax instead:

<img src='http://domain/images/someimage' alt='' />

Upvotes: 0

Zach M.
Zach M.

Reputation: 1194

One solution would be to look up the image path prior to page load and pass it to the view in a ViewBag variable. This does not fix your 500 error but you may not need to solve this issue in that way.

Controller:

public ActionResult ImagePage()
    {
       ViewBag.ImageSrc = GetMeMyImagePath();
       return View();
    }

View

<img src='@ViewBag.ImageSrc' />

Upvotes: 2

Related Questions