0

I'm using asp.net mvc 4 to build a web application.

To create url to an action I'm using ActionLink as follows:

@Html.ActionLink("Details", "Details", new { id=item.PrimaryKey })

item.PrimaryKey can be a string, so it can cointains dots or slashes or any other special character; When it contains dots or slashes i get an 404 error. ¿How can I avoid it?

I found a solution here

http://mrpmorris.blogspot.mx/2012/08/asp-mvc-encoding-route-values.html

but its complicated

¿Is there an easier solution to this?

rvazquezglez
  • 2,284
  • 28
  • 40

2 Answers2

2

I found a solution here

http://mrpmorris.blogspot.mx/2012/08/asp-mvc-encoding-route-values.html

but its complicated

That's because the problem you are attempting to solve is complicated. You may take a look at the following blog post from Scott Hanselman in which he explains the various challenges in doing this. I will summarize his conclusion:

After ALL this effort to get crazy stuff in the Request Path, it's worth mentioning that simply keeping the values as a part of the Query String (remember WAY back at the beginning of this post?) is easier, cleaner, more flexible, and more secure.

So basically if your ids can contain any characters, they should be passed as query string parameters and not part of the Uri path.

But if you insist and want to have the ids as part of the Uri path you may be inspired by how StackOverflow does it. Look at the address bar of your browser now. You will see this:

https://stackoverflow.com/questions/15697189/special-characters-in-actionlink-asp-mvc

Notice how the url contains 2 tokens: the actual id and a SEO friendly name. Jeff Atwood showed a sample filter function they are using to generate those SEO friendly slugs. The slug is just for SEO purposes. You could replace it with whatever you want and get the same result:

https://stackoverflow.com/questions/15697189/foo-bar
Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

You can use Server.UrlEncode() to encode it:

@Html.ActionLink("Details", "Details", new { id=Server.UrlEncode(item.PrimaryKey) })

reference to msdn with example

Kirill Bestemyanov
  • 11,946
  • 2
  • 24
  • 38
  • 1
    Forward slash and dots are valid url characters so them won't get escaped. :( – rvazquezglez Mar 29 '13 at 09:17
  • 1
    Server.UrlEncode won't help if the id is part of the URI path and not the query string which seems to be the case here. Not to mention that the `Html.ActionLink` already uses it internally. – Darin Dimitrov Mar 29 '13 at 11:17