如何使System.Uri不在路径中转换%2f(斜杠)?

时间:2011-04-25 00:34:17

标签: .net

System.Uri构造函数坚持将%2f序列转义为foward斜杠,当它在URL的路径部分中看到它们时。我怎么能避免这种行为?

我已经在这个问题上看过Connect票,但据我所知,解决办法对于.net 4不起作用。

3 个答案:

答案 0 :(得分:6)

它在内部保留原始字符串,例如,以下代码:

    Uri u = new Uri("http://www.example.com/path?var=value%2fvalue");
    Console.WriteLine(u.OriginalString);

将显示

http://www.example.com/path?var=value%2fvalue

编辑:我已更新Connect Link Workaround中最新.NET版本的代码。这是:

// System.UriSyntaxFlags is internal, so let's duplicate the flag privately
private const int UnEscapeDotsAndSlashes = 0x2000000;
private const int SimpleUserSyntax = 0x20000;

public static void LeaveDotsAndSlashesEscaped(Uri uri)
{
    if (uri == null)
        throw new ArgumentNullException("uri");

    FieldInfo fieldInfo = uri.GetType().GetField("m_Syntax", BindingFlags.Instance | BindingFlags.NonPublic);
    if (fieldInfo == null)
        throw new MissingFieldException("'m_Syntax' field not found");

    object uriParser = fieldInfo.GetValue(uri);
    fieldInfo = typeof(UriParser).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
    if (fieldInfo == null)
        throw new MissingFieldException("'m_Flags' field not found");

    object uriSyntaxFlags = fieldInfo.GetValue(uriParser);

    // Clear the flag that we don't want
    uriSyntaxFlags = (int)uriSyntaxFlags & ~UnEscapeDotsAndSlashes;
    uriSyntaxFlags = (int)uriSyntaxFlags & ~SimpleUserSyntax;
    fieldInfo.SetValue(uriParser, uriSyntaxFlags);
}

当然,这是一个黑客攻击,所以你应该自担风险使用它: - )

答案 1 :(得分:3)

正如我在this question中发布的那样,您可以通过配置禁用此行为:

<configuration>
  <uri>
    <schemeSettings>
      <add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes"/>
    </schemeSettings>
  </uri>
</configuration>

答案 2 :(得分:1)

在构建新URI之前尝试URI.EscapeUriString。它使%2F看起来像%252F,在我的情况下它的工作正常。