How to make System.Uri not to unescape / (slash) in path?

后端 未结 3 1823
抹茶落季
抹茶落季 2020-12-09 11:00

System.Uri constructor insists on unescaping %2f sequences as foward slashes, when it sees them in path portion of URL. How could I avoid that behaiviour?

I\'ve seen

相关标签:
3条回答
  • 2020-12-09 11:39

    It keeps the original string internally, for example, the following code:

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

    will display

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

    EDIT: I have update the code found in the Connect Link Workaround for recent .NET versions. Here it is:

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

    Of course, it's a hack, so you should use it at your own risks :-)

    0 讨论(0)
  • 2020-12-09 11:47

    Try to URI.EscapeUriString before construct new URI. It makes %2F looking like %252F and it's work just fine in my case.

    0 讨论(0)
  • 2020-12-09 11:50

    As I have posted in this question, you can disable this behaviour via a configuration:

    <configuration>
      <uri>
        <schemeSettings>
          <add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes"/>
        </schemeSettings>
      </uri>
    </configuration>
    
    0 讨论(0)
提交回复
热议问题