asp.net – How to get the URL of the current page in C#

asp.net – How to get the URL of the current page in C#

Try this :

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/>Host  + HttpContext.Current.Request.Url.Host);
Response.Write(<br/>Authority:  + HttpContext.Current.Request.Url.Authority);
Response.Write(<br/>Port:  + HttpContext.Current.Request.Url.Port);
Response.Write(<br/>AbsolutePath:  + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write(<br/>ApplicationPath:  + HttpContext.Current.Request.ApplicationPath);
Response.Write(<br/>AbsoluteUri:  + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write(<br/>PathAndQuery:  + HttpContext.Current.Request.Url.PathAndQuery);

OUTPUT

Host: localhost
Authority: localhost:60527
Port: 60527
AbsolutePath: /WebSite1test/Default2.aspx
ApplicationPath: /WebSite1test
AbsoluteUri: http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString1=2
PathAndQuery: /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 dont need to use traditional URL with query string.

http://msdn.microsoft.com/en-us/library/cc668201%28v=vs.100%29.aspx

asp.net – How to get the URL of the current page in C#

Just sharing as this was my solution thanks to Canavars 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/

Leave a Reply

Your email address will not be published.