MVC HttpUtility.UrlEncode
我正在尝试使用 HttpUtility.UrlEncode 对最终在 URL 中使用的字符串进行编码。
例如
/string/http://www.google.com
或
/string/my 测试字符串
,其中 http://www.google. com 是传递给控制器的参数。
我已经尝试过 UrlEncode 但它似乎工作不太正确,
我的路线看起来像:
routes.MapRoute(
"mStringView",
"mString/{sText}",
new { controller = "mString", action = "Index", sText = UrlParameter.Optional }
);
问题是编码位被解码,它似乎在路由中的某个地方..除了像“+”这样替换“”的东西没有被解码..
了解我的情况,其中 UrlParameter 可以是任何字符串,包括 URL。在将它们推入我的数据库之前对它们进行编码的最佳方法是什么,然后在知道它们将作为参数传递给控制器的情况下处理解码?
谢谢!
i am attempting to use HttpUtility.UrlEncode to encode strings that ultimately are used in URLs.
example
/string/http://www.google.com
or
/string/my test string
where http://www.google.com is a parameter passed to a controller.
I have tried UrlEncode but it doesn't seem to work quite right
my route looks like:
routes.MapRoute(
"mStringView",
"mString/{sText}",
new { controller = "mString", action = "Index", sText = UrlParameter.Optional }
);
The problem is the encoded bits are decoded it seems somewhere in the routing.. except things like "+" which replace " " are not decoded..
Understanding my case, where a UrlParameter can be any string, including URL's.. what is the best way to encode them before pushing them into my db, and then handling the decode knowing they will be passed to a controller as a parameter?
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
似乎这个问题在其他论坛中也出现过,一般建议是不要依赖 asp.net mvc 的标准 url 编码。优点是 url 编码不一定像我们想要的那样对用户友好,这是自定义路由 url 的目标之一。例如,这样:
可以更友好地写为
因此,自定义 url 编码除了解决此怪癖/错误之外还有其他优点。更多详细信息和示例请参见:
http ://www.dominicpettifer.co.uk/Blog/34/asp-net-mvc-and-clean-seo-friend-urls
It seems this problem has come up in other forums and the general recommendation is to not rely on standard url encoding for asp.net mvc. The advantage is url encoding is not necessarily as user friendly as we want, which is one of the goals of custom routed urls. For example, this:
can be friendlier written as
So custom url encoding has advantages beyond working around this quirk/bug. More details and examples here:
http://www.dominicpettifer.co.uk/Blog/34/asp-net-mvc-and-clean-seo-friendly-urls
您可以将参数转换为字节数组并使用 HttpServerUtility。 UrlTokenEncode
You could convert the parameter to byte array and use the HttpServerUtility.UrlTokenEncode
如果问题是“+”未解码,请使用 HttpUtility.UrlPathEncode 进行编码,解码将按需要进行。
来自HttpUtility.UrlEncode 的文档 :
If the problem is that the "+" doesn't get decoded, use HttpUtility.UrlPathEncode to encode and the decoding will work as desired.
From the documentation of HttpUtility.UrlEncode: