如何编码包含哈希的路径? [英] How to encode a path that contains a hash?

查看:159
本文介绍了如何编码包含哈希的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何正确编码的路径,包括一个散在其中(#)?注意哈希不是片段(?书签)指示,但路径名的一部分

How do you properly encode a path that includes a hash (#) in it? Note the hash is not the fragment (bookmark?) indicator but part of the path name.

例如,如果有这样的路径:

For example, if there is a path like this:

http://www.contoso.com/code/c#/somecode。 CS

这会导致问题,当您例尝试做到这一点:

It causes problems when you for example try do this:

Uri myUri = new Uri("http://www.contoso.com/code/c#/somecode.cs");



这似乎是它解释哈希的片段指标。

It would seem that it interprets the hash as the fragment indicator.

感觉不对%,23手动替换#。是否应更换有其他字符?
有在乌里一些逃脱的方法和HttpUtility但没有似乎做的伎俩。

It feels wrong to manually replace # with %23. Are there other characters that should be replaced? There are some escaping methods in Uri and HttpUtility but none seem to do the trick.

推荐答案

做了一些更多的挖朋友,发现重复的问题,对Java:
HTTP URL地址编码在Java中

Did some more digging friends and found a duplicate question for Java: HTTP URL Address Encoding in Java

但是,.NET的乌里类不提供我们所需要的构造,但在 UriBuilder 。确实

However, the .Net Uri class does not offer the constructor we need, but the UriBuilder does.

所以,为了构建一个适当的URI所在的路径包含非法字符,这样做:

So, in order to construct a proper URI where the path contains illegal characters, do this:

// Build Uri by explicitly specifying the constituent parts. This way, the hash is not confused with fragment identifier
UriBuilder uriBuilder = new UriBuilder("http", "www.contoso.com", 80, "/code/c#/somecode.cs");

Debug.WriteLine(uriBuilder.Uri);
// This outputs: http://www.contoso.com/code/c%23/somecode.cs

注意它是如何做的不可以不必要逃脱URI的部分,并不需要转义(如://部分),这是HttpUtility.UrlEncode的情况。这似乎是这个类的目的实际上是对URL的查询字符串/片断部分编码 - 而不是方案或主机名

Notice how it does not unnecessarily escape parts of the URI that does not need escaping (like the :// part) which is the case with HttpUtility.UrlEncode. It would seem that the purpose of this class is actually to encode the querystring/fragment part of the URL - not the scheme or hostname.

这篇关于如何编码包含哈希的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆