带有urlencoded字符的System.Net.Uri

Mat*_*ges 12 .net c#

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

http://feedbooks.com/type/Crime%2FMystery/books/top
Run Code Online (Sandbox Code Playgroud)

当我运行以下代码时:

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

Uri构造解码%2F成文字/,我得到一个404错误,因为它改变了网址:

http://feedbooks.com/type/Crime/Mystery/books/top
Run Code Online (Sandbox Code Playgroud)

Uri类有一个构造函数的参数dontEscape,但构造已被弃用,将其设置为true没有效果.

我的第一个想法是做一些像:

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

希望它会转换%25为文字%,但这也不起作用.

有关如何Uri在.NET中为此特定URL 创建正确对象的任何想法?

Mik*_*low 7

它在.NET 4.0中更容易一些.您可以在配置文件中设置如下设置:

<uri> 
<schemeSettings>
    <add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
</schemeSettings>
</uri>
Run Code Online (Sandbox Code Playgroud)

它仅适用于'http'和'https'方案.

或者这是LeaveDotsAndSlashesEscaped方法的新版本.它不需要特定的Uri实例,只需在应用程序启动时调用它:

private void LeaveDotsAndSlashesEscaped()
{
    var getSyntaxMethod = 
        typeof (UriParser).GetMethod("GetSyntax", BindingFlags.Static | BindingFlags.NonPublic);
    if (getSyntaxMethod == null)
    {
        throw new MissingMethodException("UriParser", "GetSyntax");
    }

    var uriParser = getSyntaxMethod.Invoke(null, new object[] { "http" });

    var setUpdatableFlagsMethod = 
        uriParser.GetType().GetMethod("SetUpdatableFlags", BindingFlags.Instance | BindingFlags.NonPublic);
    if (setUpdatableFlagsMethod == null)
    {
        throw new MissingMethodException("UriParser", "SetUpdatableFlags");
    }

    setUpdatableFlagsMethod.Invoke(uriParser, new object[] {0});
}
Run Code Online (Sandbox Code Playgroud)


小智 6

我使用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);
}
Run Code Online (Sandbox Code Playgroud)

它完美地运作.

希望这会有所帮助(迟到总比没有好!)