How to get Current Page’s Url in asp.net using code behind technique?

I want to get Url of the page like abc.aspx. how can i get this using code behind technique. Any idea.?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Full Details, you can later use string Operations for advanced manipulation:

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

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

Method 2

Use Request.RawUrl:

Gets the raw URL of the current request.

Method 3

Request.RawUrl property gives you the fully qualified URL of your current page

Method 4

You can set the current page url as Canonical tag using below way….
Here we are setting exact page url with dynamic Hostname.

for example : if you want to set canonical tag :
http://www.TestWorld.co.uk/about

In below code, Hostname will come dynamic as http://www.TestWorld.co.uk/ and Request.RawUrl will give result about, ultimately we can get purely dynamic canonical url.
Note : Here Canonical tag will create dynamically on html page, you not need to create it manually.

HtmlLink canonical = new HtmlLink();
var uri = Request.Url;
string hostName = uri.GetLeftPart(UriPartial.Authority);
canonical.Href = hostName + Request.RawUrl.ToString();
canonical.Attributes["rel"] = "canonical";
Page.Header.Controls.Add(canonical);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x