Dan*_*iel 13 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);
Run Code Online (Sandbox Code Playgroud)
结果NET4.0
http://localhost:5984/mycouchtests_pri/test%2F1
http://localhost:5984/mycouchtests_pri/test/1
Run Code Online (Sandbox Code Playgroud)
结果NET4.5
http://localhost:5984/mycouchtests_pri/test%2F1
http://localhost:5984/mycouchtests_pri/test%2F1
Run Code Online (Sandbox Code Playgroud)
因此,当使用HttpClient 由微软通过NuGet分配的请求时,如上所述,使用.Net4.0失败,因为HttpRequestMessage正在使用Uri.
任何解决方法的想法?
编辑通过添加配置,例如或(http://msdn.microsoft.com/en-us/library/ee656539(v=vs.110).aspx),
有一个非适用的解决方法.<uri>App.configMachine.config
<configuration>
<uri>
<schemeSettings>
<add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes"/>
</schemeSettings>
</uri>
</configuration>
Run Code Online (Sandbox Code Playgroud)
但由于这是一个工具库,这不是一个真正的选择.如果HttpClientfor .Net4.0应该与.Net4.5中的那个相同,它们应该具有相同的行为.
几年前,迈克·哈德洛(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});
}
Run Code Online (Sandbox Code Playgroud)
我认为它只是设置了代码中可用的标志.config,所以虽然它很hacky,但它并不是完全不受支持。