简体   繁体   English

HttpUtility.UrlEncode-减号而不是加号?

[英]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". 该路径可能类似于“ jadajada.com/我的Site.html”。

I use HttpUtility.UrlEncode to encode the urls, which is great. 我使用HttpUtility.UrlEncode对URL进行编码,这很棒。 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 ;-) (是的,我知道您可以使用string.Replace,但是请暂时避免该解决方案;-)

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. 但是,如果这仅用于显示,并且只要您的代码不依赖此值(例如,为了进行精确的子弹匹配(期望空格 )),您就可以简单地执行.Replace(" ","-")然后再编码。 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 . 空格可以URL编码为+%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. 如果要用-代替空格(不是编码),它就是替换,因此Replace方法将适合使用。

UrlEncoding will never replace a space with - on it's own, since that is not a representation of a space inside a URL. UrlEncoding永远不会单独用-代替空格,因为这不是URL内空格的表示。 It will either use + or %20. 它将使用+或%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. 因此,如果您实际上想执行此操作,那么我认为string.Replace是您的最佳选择,但是如果您不希望结果URL中包含空格,则可能应该先删除URL中的空格,然后再对其进行编码。

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). 您希望将其从+更改为-的原因之一是,当URL包含+时,URL重写将不起作用(除非您完全禁用双重转义)。 It's easier to change the + to - 将+更改为-更容易

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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