Retrieving anchor link in URL for ASP.NET

I have a URL like so:

http://localhost/place/663828/bangkok-paradise-restaurant-toronto#r306040

I am trying to see if there’s the existence of the anchor tag along with getting its value to do some code logic in the code behind.

I have been trying to use the Page.Request, but none of the properties show the anchor link portion of the URL.

For example:

Response.Write(this.Page.Request.RawUrl.ToString());

I pretty much tried the combinations/properties on this page: http://www.west-wind.com/weblog/posts/269.aspx

Just to finalize this topic:

I copied Stack Overflow’s approach with a permalink… 😀

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

It’s not possible to retrieve the #anchor from the server side in ASP.NET.

This is a client-side flag to tell the browser to move to a specific place within the page.

You can use some JavaScript code in the body onLoad event to check for an anchor and send it back to the server using Ajax.

var anchorValue;
var url = document.location;
var strippedUrl = url.toString().split("#");
if(strippedUrl.Length > 1)
    anchorvalue = strippedUrl[1];

Ref: Retrieving the anchor value from a URL

Method 2

Being more explicit, the anchor tag is never sent as part of the HTTP request by any browser. It is only interpreted locally within the browser. Neither ASP.NET nor any other web server technology, Microsoft or otherwise will see the anchor on that request.

RFC 1808
Section 2.4.1 –
“Note that the fragment identifier is not considered part of the URL.”

As others have suggested, the nearest you could get would be using client-side to read the browser window location.

Method 3

A fragment can be parsed from a URL in C# in the following way:

var uri = new Uri("http://localhost?id=2#token=23");
var fragment = uri.Fragment; // Will return #token=23

There is a problem however in that the browser won’t send fragments to the server. If you receive requests from a service that includes this information in the request, it will be available from the server side too.


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
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x