使用HttpClient的.Net4.0和.Net4.5与Uri和编码URL的方法差异 [英] How-to workaround differences with Uri and encoded URLs in .Net4.0 vs .Net4.5 using HttpClient

查看:263
本文介绍了使用HttpClient的.Net4.0和.Net4.5与Uri和编码URL的方法差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Uri behaves differently in .Net4.0 vs .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 请求分发的package / Microsoft.Net.Http /> .Net4.0失败,因为 HttpRequestMessage 使用的是 Uri

So when using the HttpClient distributed by Microsoft via NuGet requests like the above fail with .Net4.0, since the HttpRequestMessage is using the Uri.

有任何解决方法的想法吗?

Any ideas for a workaround?

编辑
存在不适用的变通办法,例如在< uri> 中添加配置 App.config Machine.config
http://msdn.microsoft.com/en-us/library/ee656539(v = vs.110).aspx )。

EDIT There is a NON APPLICABLE workaround by adding configuration for <uri> in e.g. App.config or Machine.config (http://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中的相同,则它们应该具有相同的行为。

But as this is a tools library, that's not really an option. If the HttpClient for .Net4.0 is supposed to be on par with the one in .Net4.5, they should have the same behavior.

推荐答案

Mike Hadlow写了几年前关于此的博客文章。这是他想出的解决方法:

Mike Hadlow wrote a blog post on this a few years back. Here's the code he came up with to get round 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 的代码,因此尽管它很hacky,但并非完全不受支持。

I think it just sets the flag that's available from .config in code, so while it's hacky, it's not exactly unsupported.

这篇关于使用HttpClient的.Net4.0和.Net4.5与Uri和编码URL的方法差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆