ASP.NET MVC - 创建和处理具有大于和小于字符的 URL
考虑一个指向用户个人资料页面的链接。页面正在创建如下 URL:
//Model.Name has value "<bad guy>"
Html.ActionLink("foo, "ViewUser", new { id=5, title=Url.Encode(Model.Name) })
实际结果是
http://mysite/Users/5/%253cbad%2guy%253e
当导航到该 URL 时,服务器生成 HTTP 错误 400 - 错误请求。
当使用 < 测试“有趣”的用户输入时,问题就会出现。 code>< 和 >
,但任何内容都可以来自用户,因此可以通过 Model.Name
的方式放入 URL 中。
问题: 鉴于 Model.Name
可能包含 Unicode 字符或 URL 中的非法字符:
- 去除非法字符或对它们进行编码的最佳方法是什么?
- 在将用户的输入保存到数据库之前是否应该对其进行清理,从而防止上述编码尝试?
- 当考虑让该字符串成为 URL 的一部分时,哪些字符应该被清理(即不允许)?
Consider a link to a page for a user's profile. A page is creating that URL like this:
//Model.Name has value "<bad guy>"
Html.ActionLink("foo, "ViewUser", new { id=5, title=Url.Encode(Model.Name) })
The actual outcome was
http://mysite/Users/5/%253cbad%2guy%253e
When navigating to that URL, the server generates a HTTP Error 400 - Bad Request.
The problem surfaces when testing out 'interesting' user inputs with <
and >
, but anything could come from the user, and therefore be put in a URL by way of Model.Name
.
Question:
Given that the Model.Name
may contain Unicode characters, or characters otherwise illegal in URLs:
- what's the best way to strip out illegal characters, or otherwise encode them?
- should the user's input be sanitized BEFORE being saved to the database, thereby preventing the encoding attempt above?
- which characters should be sanitized (i.e. not allowed) when thinking of having that string be part of a URL?
一种方法是对可能包含特殊字符的任何参数使用 Base 64 编码。
请参阅此处的示例:
在 ASP.Net MVC URL 参数中允许使用特殊字符
http://gathadams.com/2009/01/06/allowing-special-characters-forward-slash-hash-asterisk-etc-in-aspnet-mvc-urls/
One way is to use base 64 encoding on any parameters that might contain the special characters.
See here for an example:
Allowing special characters in ASP.Net MVC URL parameters
http://gathadams.com/2009/01/06/allowing-special-characters-forward-slash-hash-asterisk-etc-in-aspnet-mvc-urls/