Pages

2015-11-19

MVC5 ResolveUrl in static code

ASP.NET MVC5常用Url.Content(virtualPath)來取得實際的URL,若是在static程式區塊裏,要取得頁面實際路徑的簡易方式為System.Web.VirtualPathUtility.ToAbsolute(virtualPath),然而它無法處理http://路徑(會丟出例外),因此要額外處理它:

public static string ResolveUrl(string virtualPath)
{
if (virtualPath == null)
return null;

// VirtualPathUtility can't handle the http://xxx path.
if (virtualPath.IndexOf("://") != -1)
return virtualPath;

// Resolve the ~/ tilde.
if (virtualPath.StartsWith("~"))
return System.Web.VirtualPathUtility.ToAbsolute(virtualPath);

return virtualPath;
}

No comments: