C# 如何使用HttpClient解决.Net4.0与.Net4.5中Uri和编码URL的差异

C# 如何使用HttpClient解决.Net4.0与.Net4.5中Uri和编码URL的差异,c#,.net-4.0,dotnet-httpclient,C#,.net 4.0,Dotnet Httpclient,Uri在.Net4.0和.Net4.5中的行为不同 var u = new Uri("http://localhost:5984/mycouchtests_pri/test%2F1"); Console.WriteLine(u.OriginalString); Console.WriteLine(u.AbsoluteUri); 结果NET4.0 http://localhost:5984/mycouchtests_pri/test%2F1 http://localhost:5984/mycou

Uri
在.Net4.0和.Net4.5中的行为不同

var u = new Uri("http://localhost:5984/mycouchtests_pri/test%2F1");
Console.WriteLine(u.OriginalString);
Console.WriteLine(u.AbsoluteUri);
结果NET4.0

http://localhost:5984/mycouchtests_pri/test%2F1
http://localhost:5984/mycouchtests_pri/test/1
结果NET4.5

http://localhost:5984/mycouchtests_pri/test%2F1
http://localhost:5984/mycouchtests_pri/test%2F1
因此,当使用
HttpClient
时,上述请求会在.Net4.0中失败,因为
HttpRequestMessage
正在使用
Uri

有什么解决办法吗

编辑 有一个不适用的解决方法,即在
App.config
Machine.config
()中添加
的配置


但由于这是一个工具库,所以这不是一个真正的选项。如果.NET4.0的.<代码> HTTPclipse < /代码>应该与.NET4.5中的一个相同,它们应该有相同的行为。

< P> Mike Hadlow几年前写道。这是他想出的绕过这个问题的密码:

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

我认为它只是在代码中设置了可从
.config
获得的标志,因此,虽然它有黑客行为,但并不完全不受支持。

您可以看到
u.OriginalString
给出了相同的值,而与.net frameword无关,因此您只能使用它,除非您确实需要另一个,如果我错了,请纠正我!我没有控制权。URI在HttpClient和相关消息处理程序的黑暗地带被使用。我想,您关心的是使用
OriginalString
vs
AbsoluteUri
,但我仍然不清楚,因为你需要解决这个问题!我关心的是能够将带有上述URL的
Uri
传递到
HttpRequestMessage
。我注意到它在.Net4.0和4.5之间有不同的行为,因此我开始深入研究,发现上面的内容,并猜测它们在这两个实现中选择了不同的内容-这与配置文件有着相同的问题:它修改了整个AppDomain的设置。谢谢,我在其他地方偶然发现了这一点。这也是一种解决方法,但我不想称之为,在这种情况下,使用者必须在引导模式或其他模式下进行操作,因为它可能“影响”同一域中其他正在运行的lib。
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});
}