How to get the URL of the current page in C#
This question already has an answer here:
尝试这个 :
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx
string host = HttpContext.Current.Request.Url.Host;
// localhost
You may at times need to get different values from URL.
Below example shows different ways of extracting different parts of URL
EXAMPLE: (Sample URL)
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
CODE
Response.Write("<br/> " + HttpContext.Current.Request.Url.Host);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Authority);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Port);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write("<br/> " + HttpContext.Current.Request.ApplicationPath);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write("<br/> " + HttpContext.Current.Request.Url.PathAndQuery);
OUTPUT
localhost
localhost:60527
60527
/WebSite1test/Default2.aspx
/WebSite1test
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString1=2
/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
You can copy paste above sample code & run it in asp.net web form application with different URL.
I also recommend reading ASP.Net Routing in case you may use ASP Routing then you don't need to use traditional URL with query string.
http://msdn.microsoft.com/en-us/library/cc668201%28v=vs.100%29.aspx
Just sharing as this was my solution thanks to Canavar's post.
If you have something like this:
"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"
or like this:
"https://www.something.com/index.html?a=123&b=4567"
and you only want the part that a user would type in then this will work:
String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");
which would result in these:
"http://localhost:1234/"
"https://www.something.com/"
链接地址: http://www.djcxy.com/p/21412.html
上一篇: 用更好的浏览器替代.NET WebBrowser控件,如Chrome?
下一篇: 如何在C#中获取当前页面的URL