简体   繁体   中英

HttpUtility.UrlEncode - Minus instead of plus?

I am in a sitauation where I have some path. This path could be something like "jadajada.com/My Site.html".

I use HttpUtility.UrlEncode to encode the urls, which is great. However, I have the issue that whenever I have a space, it replaces this with a "+" sign. I need a "-" sign instead.

Can this method perform this task? And if so, what kind of encoding ect.

(And yes, I know you can use string.Replace, but please avoid that solution for now ;-)

Replacing spaces with "-" is not really encoding , since there is no standard decoder for that; the "+" is correct.

However, if this is for display only, and as long as your code doesn't rely on this value (for example, to do an exact slug match expecting the space ) you could simply do a .Replace(" ","-") before you encode. In that lossy scenario you might also want to replace a few others, truncate overly long strings, etc.

Encoding it once it has a - should be a no-op (ie it won't change).

A space can be URL encoded either as a + or as %20 . That is the way that a space is encoded, so there is no built in method for encoding it into any other arbitrary character.

If you want to replace spaces with - instead that is not encoding, it's replacing, so the Replace method would be appropriate to use.

UrlEncoding will never replace a space with - on it's own, since that is not a representation of a space inside a URL. It will either use + or %20.

So if you actually want to do this, I think that string.Replace is your best option here, but if you do not want spaces inside the resulting URL, you should probably remove the spaces from the URL before you encode it in the first place.

One reason that you'd want to change it from + to - is that URL Rewriting doesn't work when the URL contains + (unless you entirely disable double escaping). It's easier to change the + to -

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM