Getting ASP.NET MVC to correctly remove the # character (hash / pound) in routes

I have a route that looks like this:

routes.MapRoute( "BlogTags", "Blog/Tags/{tag}", new { controller = "Blog", action = "BrowseTag", viewRss = false } ); 

And I am creating a URL using this route as follows:

 <%= Html.RouteLink(Html.Encode(sortedTags[i].Tag), new { action = "BrowseTag", tag = sortedTags[i].Tag })%> 

However, when using a tag with the # character (for example, "C #"), the routing mechanism does not hide it, so I get a URL that looks like this:

 <a href="/Blog/Tags/C#">C#</a> 

I need # to be escaped so that it looks like this:

 <a href="/Blog/Tags/C%23">C#</a> 

I tried to make Url.Encode in the tag before it entered the route, for example:

 <%= Html.RouteLink(Html.Encode(sortedTags[i].Tag), new { action = "BrowseTag", tag = Url.Encode(sortedTags[i].Tag) })%> 

But this makes the routing mechanism double escape # (which causes ASP.NET to crash with an invalid request error):

 <a href="/Blog/Tags/C%2523">C#</a> 

How can I make the routing mechanism escape this # character for me correctly?

Thank you for your help.

+6
c # asp.net-mvc url-routing
source share
2 answers

As a very bald solution, I would manually replace "#" with "% 23" on the output of RouteLink. If you do not use snippets in your URLs, they should work.

You can use regex to apply only replacements to the last part of your URL.

+1
source share

I have a similar SO question regarding "/". Studying this issue, I found out that ASP.NET decodes URL values ​​before they are passed to the MVC structure, and since "#" has a special meaning for URLs (just like the "/" with which I dealt) there are good chances that something in the basic routing engine causes this behavior.

As Levy mentioned in his comment, one solution is to use ASP.NET 4.0. Another solution would be to write a RouteLink helper that automatically replaces "#" with some marker (for example, "! MY_HASH_TOKEN!"), And then cancels this replacement in your controller (or perhaps through some HttpModule).

Or just drop the towel and pass the tag value as an argument to the request. Not so sexy, but simple and it works.

0
source share

All Articles