[英]How to get URL path in C#
我想得到URL的所有路徑,除了url的當前頁面,例如:我的URL是http://www.MyIpAddress.com/red/green/default.aspx我想得到“ http:// www。僅限MyIpAddress.com/red/green/ 。 我怎么能得到。我在做什么
string sPath = new Uri(HttpContext.Current.Request.Url.AbsoluteUri).OriginalString; System.Web.HttpContext.Current.Request.Url.AbsolutePath;
sPath = sPath.Replace("http://", "");
System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
string sRet = oInfo.Name;
Response.Write(sPath.Replace(sRet, ""));
它在新的System.IO.FileInfo(sPath)上顯示異常,因為sPath包含“localhost / red / green / default.aspx”,表示“不支持給定路徑的格式”。
主要網址: http:// localhost:8080 / mysite / page.aspx?p1 = 1&p2 = 2
在C#中獲取URL的不同部分。
Value of HttpContext.Current.Request.Url.Host
localhost
Value of HttpContext.Current.Request.Url.Authority
localhost:8080
Value of HttpContext.Current.Request.Url.AbsolutePath
/mysite/page.aspx
Value of HttpContext.Current.Request.ApplicationPath
/mysite
Value of HttpContext.Current.Request.Url.AbsoluteUri
http://localhost:8080/mysite/page.aspx?p1=1&p2=2
Value of HttpContext.Current.Request.RawUrl
/mysite/page.aspx?p1=1&p2=2
Value of HttpContext.Current.Request.Url.PathAndQuery
/mysite/page.aspx?p1=1&p2=2
不要將其視為URI問題,將其視為字符串問題。 然后它很好很容易。
String originalPath = new Uri(HttpContext.Current.Request.Url.AbsoluteUri).OriginalString;
String parentDirectory = originalPath.Substring(0, originalPath.LastIndexOf("/"));
真的很容易!
編輯添加缺失的括號。
替換這個:
string sRet = oInfo.Name;
Response.Write(sPath.Replace(sRet, ""));
有以下幾點:
string sRet = oInfo.Name;
int lastindex = sRet.LastIndexOf("/");
sRet=sRet.Substring(0,lastindex)
Response.Write(sPath.Replace(sRet, ""));
用這個
string sPath = (HttpContext.Current.Request.Url).ToString();
sPath = sPath.Replace("http://", "");
var oInfo = new System.IO.FileInfo(HttpContext.Current.Request.RawUrl);
string sRet = oInfo.Name;
Response.Write(sPath.Replace(sRet, ""));
如果你只想嘗試導航到你網站上的另一個頁面,這可能會讓你想要你想要的,但如果你真的需要它,它就不會得到絕對的路徑。 您可以在站點內導航而不使用絕對路徑。
string loc = "";
loc = HttpContext.Current.Request.ApplicationPath + "/NewDestinationPage.aspx";
Response.Redirect(loc, true);
如果你真的需要絕對路徑,你可以選擇部件並用Uri類構建你需要的東西:
Uri myUri = new Uri(HttpContext.Current.Request.Url.AbsoluteUri)
myUri.Scheme
myUri.Host // or DnsSafeHost
myUri.Port
myUri.GetLeftPart(UriPartial.Authority) // etc.
關於ASP.NET路徑主題的好文章 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.