c# - WebClient 不会自动重定向

标签 c# webclient

当使用 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 请求。

我的网络客户端处理程序

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 请求。 [在浏览器中自动生成]

最佳答案

尝试添加

request.AllowAutoRedirect = true;

就在

var request = base.GetWebRequest(address);

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

关于c# - WebClient 不会自动重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13039068/

相关文章:

java - bodyToMono ParameterizedTypeReference 和 bodyToFlux 有什么区别

c# - 如何避免以下重复代码?

c# - 从后台调用?

c# - 以编程方式将系列添加到 XAML 中定义的 OxyPlot

C# 从运行时使用 jQuery 更改的代码中获取元素的背景颜色

c# - Fluent nHibernate 保存或更新派生实体

c# - 将 WebClient 转换为 HttpClient

c# - 图像按钮上的边框

c# - 使用 webclient 类将文件上传到文件服务器

.net - .net 中 Python 的 urllib 等效项