【问题标题】:Exception on 302 redirect HTTPS to HTTP after POST in Windows Phone 8.1在 Windows Phone 8.1 中 POST 后 302 将 HTTPS 重定向到 HTTP 的异常
【发布时间】:2015-01-07 01:48:35
【问题描述】:

我正在尝试创建一个 Windows Phone 8.1 应用程序,该应用程序使用 POST 请求(使用 Windows.Web.Http)登录到网站,然后继续到另一个页面。里面当然还有很多代码,但我认为这与本次讨论无关。

HttpClient httpClient = new HttpClient();
...
HttpResponseMessage myHttpPostResponse = await httpClient.PostAsync(myUri,postContent);

我无法克服的挑战是在收到响应之前抛出异常。这是我在即时窗口中收到的消息:

A first chance exception of type 'System.Exception' occurred in mscorlib.ni.dll
System.Exception: Exception from HRESULT: 0x80072F08
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at App1.MainPage.<getSJWasync>d__1.MoveNext()

我的搜索让我相信这是由于网络服务器从 https 登录页面执行 302 重定向到非安全 http 页面...

在 MSDN 上找到...

“ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR 12040 (2F08) 由于重定向,应用程序正在从 SSL 移动到非 SSL 连接。"

在我的 PC 上使用 Chrome 开发人员工具,我可以看到在 POST 之后确实有一个 302 重定向。我试图通过不允许自动重定向(在 HttpBaseProtocolFilter 中)来手动处理重定向,但仍然抛出该异常。我尝试使用 try/catch 处理异常,但我不知道如何仍然获取 HttpResponseMessage。

【问题讨论】:

    标签: c# windows-phone-8.1 http-redirect hresult


    【解决方案1】:

    HttpBaseProtocolFilter 中禁用自动重定向应该会阻止HttpClient 抛出异常。

    这是一个例子:

    Uri uri = new Uri(
        "https://http2.cloudapp.net/?status=302&name=Location&value=http%3a%2f%2fkiewic.com");
    HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
    
    // Only needed to be able to connect to test server.
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
    
    // Turn off auto-redirections.
    filter.AllowAutoRedirect = false;
    
    HttpClient client = new HttpClient(filter);
    HttpStringContent content = new HttpStringContent("blah");
    HttpResponseMessage response = await client.PostAsync(uri, content);
    
    // Redirect URL is here.
    Debug.WriteLine(response.Headers["Location"]);
    

    【讨论】:

    • 啊哈!您的示例代码指出了我的方式的错误......当我声明 HttpClient 的新实例时,我没有放入过滤器。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    相关资源
    最近更新 更多