Url encoding quotes and spaces

Samo picture Samo · Jan 27, 2011 · Viewed 45.3k times · Source

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?

Answer

porges picture porges · Jan 27, 2011

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

Uri.EscapeDataString should do what you want.