gpt4 book ai didi

.net - 如何使Uri.EscapeDataString符合RFC 3986

转载 作者:行者123 更新时间:2023-12-03 09:08:43 27 4
gpt4 key购买 nike

Uri类默认为RFC2396。对于OpenID和OAuth,我需要与RFC 3986一致的Uri转义。

System.Uri class documentation:

By default, any reserved characters in the URI are escaped in accordance with RFC 2396. This behavior changes if International Resource Identifiers or International Domain Name parsing is enabled in which case reserved characters in the URI are escaped in accordance with RFC 3986 and RFC 3987.



该文档还指出,激活此IRI模式并从而激活RFC 3986行为意味着将uri节元素添加到machine.config并将其添加到您的app / web.config文件中:
<configuration>
<uri>
<idn enabled="All" />
<iriParsing enabled="true" />
</uri>
</configuration>

但是,无论是否存在.config文件中,.NET 3.5 SP1应用程序都具有相同的(非3986)转义行为。 我还需要做些什么才能使Uri.EscapeDataString使用RFC 3986规则? (具体来说,是转义该RFC中定义的保留字符)

最佳答案

由于无法让Uri.EscapeDataString采取RFC 3986行为,因此我编写了自己的符合RFC 3986的转义方法。它利用Uri.EscapeDataString,然后将转义“升级”到RFC 3986合规性。

/// <summary>
/// The set of characters that are unreserved in RFC 2396 but are NOT unreserved in RFC 3986.
/// </summary>
private static readonly string[] UriRfc3986CharsToEscape = new[] { "!", "*", "'", "(", ")" };

/// <summary>
/// Escapes a string according to the URI data string rules given in RFC 3986.
/// </summary>
/// <param name="value">The value to escape.</param>
/// <returns>The escaped value.</returns>
/// <remarks>
/// The <see cref="Uri.EscapeDataString"/> method is <i>supposed</i> to take on
/// RFC 3986 behavior if certain elements are present in a .config file. Even if this
/// actually worked (which in my experiments it <i>doesn't</i>), we can't rely on every
/// host actually having this configuration element present.
/// </remarks>
internal static string EscapeUriDataStringRfc3986(string value) {
// Start with RFC 2396 escaping by calling the .NET method to do the work.
// This MAY sometimes exhibit RFC 3986 behavior (according to the documentation).
// If it does, the escaping we do that follows it will be a no-op since the
// characters we search for to replace can't possibly exist in the string.
StringBuilder escaped = new StringBuilder(Uri.EscapeDataString(value));

// Upgrade the escaping to RFC 3986, if necessary.
for (int i = 0; i < UriRfc3986CharsToEscape.Length; i++) {
escaped.Replace(UriRfc3986CharsToEscape[i], Uri.HexEscape(UriRfc3986CharsToEscape[i][0]));
}

// Return the fully-RFC3986-escaped string.
return escaped.ToString();
}

关于.net - 如何使Uri.EscapeDataString符合RFC 3986,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/846487/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com