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

问题描述 投票:13回答:1

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 distributed by Microsoft via NuGet请求时,如上所述失败.Net4.0,因为HttpRequestMessage使用Uri

任何解决方法的想法?

编辑通过在例如<uri>中添加配置,有一种非适用的解决方法。 App.configMachine.confighttp://msdn.microsoft.com/en-us/library/ee656539(v=vs.110).aspx)。

<configuration>
  <uri>
    <schemeSettings>
      <add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes"/>
    </schemeSettings>
  </uri>
</configuration>

但由于这是一个工具库,这不是一个真正的选择。如果.Net4.0的HttpClient应该与.Net4.5中的那个相同,那么它们应该具有相同的行为。

c# .net-4.0 dotnet-httpclient
1个回答
1
投票

几年前Mike Hadlow写了a blog post on this。这是他想出的代码来解决这个问题:

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在代码中可用的标志,所以虽然它很骇人听闻,但它并不完全不受支持。

© www.soinside.com 2019 - 2024. All rights reserved.