【问题标题】:WebClient Does not automatically redirectWebClient 不会自动重定向
【发布时间】:2012-10-23 20:54:10
【问题描述】:

使用 Firebug 记录登录过程时,我看到它是这样的

POST //The normal post request
GET //Automatically made after the login
GET //Automatically made after the login
GET //Automatically made after the login

当使用我下面的代码发出发布请求时,它没有发出浏览器正在执行的自动 GET 请求。

我的 WebClient 处理程序

using System;
using System.Net;

namespace Test
{
    class HttpHandler : WebClient
    {
        private CookieContainer _mContainer = new CookieContainer();

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = _mContainer;
            }
            return request;
        }

        protected override WebResponse GetWebResponse(WebRequest request)
        {
            var response = base.GetWebResponse(request);
            if (response is HttpWebResponse)
                _mContainer.Add((response as HttpWebResponse).Cookies);
            return response;
        }

        public void ClearCookies()
        {
            _mContainer = new CookieContainer();
        }
    }
}

使用代码

private static async Task<byte[]> LoginAsync(string username, string password)
{
    var postData = new NameValueCollection();
    var uri = new Uri(string.Format("http://{0}/", ServerName));

    postData.Add("name", username);
    postData.Add("password", password);

    return await HttpHandler.UploadValuesTaskAsync(uri, postData);
}

当尝试跟踪我的应用程序的连接时,它只执行 POST 请求,而不执行其余的 GET 请求。 [在浏览器中自动生成]

【问题讨论】:

  • 在同步版本中也会失败吗?使用 AllowAutoRedirect,我希望它可以工作......可能是从 POST 重定向的问题?

标签: c# webclient


【解决方案1】:

尝试添加

request.AllowAutoRedirect = true;

就在下面

var request = base.GetWebRequest(address);

它为我解决了一些类似的问题,尽管默认情况下 AllowAutoRedirect 应该是 true

【讨论】:

    【解决方案2】:

    这不足为奇,因为HttpWebRequest 不是浏览器。如果您需要执行这些重定向,请检查HttpWebResponse.StatusCode,如果是redirect code in the 300's,请发出另一个请求。注意10.3 Redirection 3xx下的链接:

    此类状态码表示用户代理需要采取进一步的行动才能满足请求。当且仅当第二个请求中使用的方法是 GET 或 HEAD 时,用户代理可以执行所需的操作,而无需与用户交互。客户端应该检测无限重定向循环,因为这样的循环会为每个重定向生成网络流量。

    【讨论】:

    • 网络客户端确实自动将 AllowAutoRedirect 设为 true
    • @dbaseman 我问的是 WebClient 不是派生的 HttpWebResponse&Request
    • @TorlanOther:嗯,在你的示例代码中没有任何地方引用 WebClient 并没有帮助......
    • @JonSkeet 你错了,他的类是从WebCLient派生的。
    • @data_smith: 是的,虽然我怀疑 HttpWebRequest 负责重定向...
    猜你喜欢
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 2022-10-06
    • 2013-05-01
    • 2015-09-03
    相关资源
    最近更新 更多