Url encoding quotes and spaces

白昼怎懂夜的黑 提交于 2019-11-28 18:59:08

问题


I have some query text that is being encoded with JavaScript, but I've encountered a use case where I might have to encode the same text on the server side, and the encoding that's happening is not the same. I need it to be the same. Here's an example.

I enter "I like food" into the search box and hit the search button. JavaScript encodes this as %22I%20like%20food%22

Let's say I get the same value as a string on a request object on the server side. It will look like this: "\"I like food\""

When I use HttpUtility.UrlEncode(value), the result is "%22I+like+food%22". If I use HttpUtility.UrlPathEncode(value), the result is "\"I%20like%20food\""

So UrlEncode is encoding my quotes but is using the + character for spaces. UrlPathEncode is encoding my spaces but is not encoding my escaped quotes.

I really need it to do both, otherwise the Search code completely borks on me (and I have no control over the search code).

Tips?


回答1:


UrlPathEncode doesn't escape " because they don't need to be escaped in path components.

Uri.EscapeDataString should do what you want.




回答2:


There are a few options available to you, the fastest might be to use UrlEncode then do a string.replace to swap the + characters with %20.

Something like

HttpUtility.UrlEncode(input).Replace("+", "%20");



回答3:


WebUtility.UrlEncode(str)

Will encode all characters that need encoded using the %XX format, including space.



来源:https://stackoverflow.com/questions/4820167/url-encoding-quotes-and-spaces

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