1. 程式人生 > >asp.net專案中根據給出的相對地址獲取網站絕對地址的C#程式碼

asp.net專案中根據給出的相對地址獲取網站絕對地址的C#程式碼

這段C#程式碼在ASP.NET的專案中可以根據給定的相對地址獲取絕對訪問地址,例如:給出 /codes/index.aspx 可以返回http://www.sharejs.com/codes/index.aspx的絕對地址結果。

/// <summary>
/// 根據給出的相對地址獲取網站絕對地址
/// </summary>
/// <param name="localPath">相對地址</param>
/// <returns>絕對地址</returns>
public static string GetWebPath(
string localPath)
{
string path = HttpContext.Current.Request.ApplicationPath;
string thisPath;
string thisLocalPath;
//如果不是根目錄就加上"/" 根目錄自己會加"/"
if (path != "/")
{
thisPath = path + "/";
}
else
{
thisPath = path;
}
if (localPath.StartsWith("~/"))
{
thisLocalPath = localPath.Substring(2);
}
else
{
return localPath;
}
return thisPath + thisLocalPath;
}