ASP.NET MVC Colon in URL

天大地大妈咪最大 提交于 2019-12-01 05:16:17

Consider URL encoding and decoding your movie titles.

You'd end up with foo.com/bar/Bob%58The%20Return

As an alternative, consider leveraging an HTML helper to remove URL unfriendly characters in URLs (method is URLFriendly()). The SEO benefits between a colon and a placeholder (e.g. a dash) would likely be negligable.

I resolved this issue by adding this to my web.config:

<httpRuntime requestPathInvalidCharacters=""/>

This must be within the system.web section.

The default is:

<httpRuntime requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,:,\,?"/>

So to only make an exception for the colon it would become

<httpRuntime requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,\,?"/>

Read more at: http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.requestpathinvalidcharacters.aspx

For what I understand the colon character is acceptable as an unencoded character in an URL. I don't know why they added it to the default of the requestPathInvalidCharacters.

Andy Skirrow

One of the biggest worries with your approach is that the movie name isn't always going to be unique (e.g. "The Italian Job"). Also what about other ilegal characters (e.g. brackets etc).

It might be a good idea to use an id number in the url to locate the movie in your database. You could still include a url friendly copy of movie name in your url, but you wouldn't need to worry about getting back to the original title with all the illegal characters in it.

A good example is the url to this page. You can see that removing the title of the page still works:

ASP.NET MVC Colon in URL

ASP.NET MVC Colon in URL

Colon is a reserved and invalid character in an URI according to the RFC 3986. So don't do something that violates the specification. You need to either URL encode it or use another character. And here's a nice blog post you might take a look at.

The simplest way is to use System.Web.HttpUtility.UrlEncode() when building the url and System.Web.HttpUtility.UrlDecode when interpreting the results coming back. You would also have problems with the space character if you don't encode the value first.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!