System.Net.Uri与urlen codeD字符字符、Net、System、Uri

2023-09-04 00:24:03 作者:顾执

我需要请求以下URL我的应用程序中:

I need to request the following URL inside my application:

http://feedbooks.com/type/Crime%2FMystery/books/top

当我运行下面的code:

When I run the following code:

Uri myUri = new Uri("http://feedbooks.com/type/Crime%2FMystery/books/top");

乌里构造德codeS的%2F 成文字 / ,我得到一个404错误,因为它改变了网址为:

The Uri constructor decodes the %2F into a literal /, and I get a 404 error because it has changed the URL to:

http://feedbooks.com/type/Crime/Mystery/books/top

乌里类有一个构造函数参数 dontEscape ,但是构造器是德precated并将其设置为不起任何作用。

The Uri class has a constructor that takes a parameter dontEscape, but that constructor is deprecated and setting it to true has no effect.

我首先想到的是做这样的事情:

My first thought was to do something like:

Uri myUri = new Uri("http://feedbooks.com/type/Crime%252FMystery/books/top");

通过的希望,这将转化 25%成文字,但没有任何工作

With the hopes that it would convert %25 into a literal %, but that didn't work either.

任何想法如何建立一个正确的乌里对象在.NET中这个特定的网址是什么?

Any ideas how to create a correct Uri object for this particular URL in .NET?

推荐答案

我跑进使用2.0同样的问题...

I ran into the same problem using 2.0...

我发现张贴在这个博客:

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

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;

    fieldInfo.SetValue(uriParser, uriSyntaxFlags);
}

它完美。

希望这有助于(迟到总比不到好!)

Hope this helps (better late than never!)