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

发布于 2024-10-30 04:44:59 字数 240 浏览 4 评论 0原文

我现在的处境是有出路的。该路径可能类似于“jadajada.com/My Site.html”。

我使用 HttpUtility.UrlEncode 对 url 进行编码,这很棒。但是,我有一个问题,每当我有空格时,它就会用“+”号替换它。我需要一个“-”号来代替。

这个方法可以完成这个任务吗?如果是这样,是什么样的编码等。

(是的,我知道您可以使用 string.Replace,但请暂时避免使用该解决方案;-)

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 ;-)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

桃扇骨 2024-11-06 04:44:59

“-”替换空格并不是真正的编码,因为没有标准的解码器; "+" 是正确的。

但是,如果这仅用于显示,并且只要您的代码不依赖于该值(例如,进行精确的 slug 匹配,需要空格)您可以在编码之前简单地执行 .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. 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 (i.e. it won't change).

北方的韩爷 2024-11-06 04:44:59

空格可以被 URL 编码为 +%20。这就是空格的编码方式,因此没有内置方法可以将其编码为任何其他任意字符。

如果您想用 - 替换空格,而不是编码,而是替换,因此适合使用 Replace 方法。

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.

假装不在乎 2024-11-06 04:44:59

UrlEncoding 永远不会用 - 本身替换空格,因为这不是 URL 内空格的表示。它将使用 + 或 %20。

因此,如果您确实想这样做,我认为 string.Replace 是您的最佳选择,但如果您不希望生成的 URL 中包含空格,则可能应该在之前从 URL 中删除空格您首先对其进行编码。

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.

最后的乘客 2024-11-06 04:44:59

您希望将其从 + 更改为 - 的原因之一是,当 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). It's easier to change the + to -

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文