0

我试图在 Windows 应用商店应用程序上发送 POST 请求。我试图用 Fiddler 或 Charles 来捕捉它。

  • Fiddler/Charles 关闭后,一切正常。
  • 打开 Fiddler/Charles,PostAsync()引发异常

这是我的尝试:

Uri uri = new Uri("http://example.com");
using (StringContent content = new StringContent("{}", Encoding.UTF8, "application/json"))
{
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Host = uri.Host;
        try
        {
            using (HttpResponseMessage response = await client.PostAsync(uri, content))
            {
                if (response.IsSuccessStatusCode)
                {
                    String result = await response.Content.ReadAsStringAsync();
                    return result;
                }
                return null;
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}

为什么我无法使用 fiddler 或 Charles 来分析流量?这是我得到的例外:

Data    {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
HelpLink    null    string
HResult -2146233088 int
InnerException  {"The underlying connection was closed: Unable to connect to the remote server."}   System.Exception {System.Net.WebException}
IPForWatsonBuckets  206848215   System.UIntPtr
IsTransient false   bool
Message "An error occurred while sending the request."  string
RemoteStackTrace    null    string
Source  "mscorlib"  string
StackTrace  "   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at Example.Services.ExampleServices.<ExampleClass>d__3.MoveNext() in c:\\TFS\\Example\\ExampleMain\\Example\\Services\\ExampleServices.cs:line 110"   string
TargetSite  {Void Throw()}  System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}
WatsonBuckets   null    object
4

2 回答 2

1

我找到了问题的根源和解决方案:不能手动定义Host 标头以使请求在 Fiddler 或 Charles 处于活动状态的环境中工作。

这意味着我们必须删除或注释掉以下行:

client.DefaultRequestHeaders.Host = uri.Host;

通过不自己设置主机,您的应用程序将神奇地再次使用本地代理工作,并且框架将自行设置主机标头。

这对于那些可能已经按照最近的微软指南做错的人很有用:http: //blogs.msdn.com/b/wsdevsol/archive/2013/02/05/how-to-use-httpclient- to-post-json-data.aspx

于 2013-05-23T14:16:37.863 回答
0

您是否忘记授予您的应用程序AppContainer Loopback 豁免

您是否忘记配置机器以信任 Fiddler 的根证书?

于 2013-05-22T19:10:26.770 回答