GGO
GGO

Reputation: 2748

Equivalent Server.MapPath for http query

I have an .net Mvc application started with http://localhost:1234. In production the url is http://mywebsite/mysubfolder.

In a HelperExtension i have a method rendering image path like :

public static MvcHtmlString DisplayPicture(this HtmlHelper html, string model)
{ 
    [...]
    return new MvcHtmlString("<img src=\"/Content/images/image.png\" />");
}

In local, no problem, but in production, browser search to load http://mywebsite/Content/images/image.png instead of http://mywebsite/mysubfolder/Content/images/image.png.

So, i'm searching an equivalent of Server.MapPath for http query to generate automatically the correct picture url. Thanks

Upvotes: 2

Views: 502

Answers (2)

EFAV
EFAV

Reputation: 61

You could use this generic extension method passing path and Request parameter, returning Http URI

public static class RequestExtension
{
    public static string MapHttpPath(this HttpRequest currentRequest, string path)
    {
        if (string.IsNullOrEmpty(path)) return null;

        path = path.Replace("~", "");
        if (path.StartsWith("/"))
            path = path.Substring(1, path.Length - 1);

        return string.Format("{0}://{1}{2}/{3}",
            currentRequest.Url.Scheme,
            currentRequest.Url.Authority,
            System.Web.HttpRuntime.AppDomainAppVirtualPath == "/" ? "" : System.Web.HttpRuntime.AppDomainAppVirtualPath,
            path);
    }
}

Upvotes: 1

akerra
akerra

Reputation: 1200

The following code will return your application base path, no matter how many route values are in your current path:

public string GetBasePath()
{
    var uri = System.Web.HttpContext.Current.Request.Url;
    var vpa = System.Web.HttpRuntime.AppDomainAppVirtualPath;
    url = string.Format("{0}://{1}{2}", uri.Scheme, uri.Authority, vpa == "/" ? string.Empty : vpa);

    return url;
}

After creating the above method, change your code accordingly:

public static MvcHtmlString DisplayPicture(this HtmlHelper html, string model)
{ 
    [...]
    string basePath = GetBasePath();
    return new MvcHtmlString("<img src=\"" + basePath + "/Content/images/image.png\" />");
}

Upvotes: 0

Related Questions