Advertisement
Advertisement


How to get the URL of the current page in C#


Question

Can anyone help out me in getting the URL of the current working page of ASP.NET in C#?

2011/11/03
1
660
11/3/2011 9:40:20 PM


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

2020/06/20

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/"
2012/04/26

if you just want the part between http:// and the first slash

string url = Request.Url.Host;

would return stackoverflow.com if called from this page

Here's the complete breakdown

2009/02/27

the request.rawurl will gives the content of current page it gives the exact path that you required

use HttpContext.Current.Request.RawUrl

2015/01/08

If you want to get

localhost:2806 

from

http://localhost:2806/Pages/ 

then use:

HttpContext.Current.Request.Url.Authority
2013/01/17

Source: https://stackoverflow.com/questions/593709
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]