2017-10-09 52 views
2

我有一個以http://localhost:1234開頭的.net Mvc應用程序。 在生產中的網址是http://mywebsite/mysubfolder用於http查詢的等效Server.MapPath

在HelperExtension我有這樣的方法繪製圖像路徑:

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

在本地,沒有問題,但在生產中,瀏覽器搜索加載http://mywebsite/Content/images/image.png,而不是http://mywebsite/mysubfolder/Content/images/image.png

所以,我正在尋找相當於Server.MapPath的http查詢來自動生成正確的圖片url。由於

回答

1

您可以使用此通用擴展方法傳遞路徑和請求參數,返回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); 
    } 
} 
0

下面的代碼將返回您的應用程序的基本路徑,無論路由值有多少是你的當前位置:

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

創建上述方法後,相應地更改代碼:

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