WebClient.UploadFileASync 的非常奇怪的行为

Very strange behaviour with WebClient.UploadFileASync

我将身份验证 cookie 存储到我的应用程序中的静态 CookieContainer 中,感谢关于此 link (1)

的回答

我实现了在 DocumentCompleted 事件上获取 CookieContainer 的代码:

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        if (!this.webBrowser1.Document.Title.Replace(" ", string.Empty).ToLower().Contains("xxx"))
        {
            CookieContainer ck =  GetUriCookieContainer(this.webBrowser1.Url);

            validSession = ck;

            Succeeded = true;
            this.Close();
        }
    }

因为我正在使用 WebClient,所以我需要创建它的扩展以便它可以存储 CookieContainer:

public class WebClientEx : WebClient
{
    public WebClientEx()
        : this(new CookieContainer())
    { }

    public WebClientEx(CookieContainer c)
    {
        this.CookieContainer = c;
    }

    public CookieContainer CookieContainer { get; set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);

        var castRequest = request as HttpWebRequest;
        if (castRequest != null)
        {
                castRequest.CookieContainer = this.CookieContainer;
        }

        return request;
    }
}

(1) 存储 CookieContainer 后,我无需身份验证即可请求页面的任何内容:

        WebClientEx e = new WebClientEx(validSession);
        string x = e.UploadString(new Uri("http://localhost:14590/default.aspx"), "ola");
        // x now contains the html page of default.aspx

问题是当我尝试使用 UploadFileAsync 将文件上传到服务器时,我将尝试逐步描述问题:

但是请查看这些步骤,上传功能将正常运行:

我不明白为什么会这样?你知道为什么吗?请注意,如果我使用 WebClient.UploadString() 等其他方法,如果 cookieContainer 可用,则不会重定向回登录页面。

由于某些未知原因,CookieContainer 导致了这个问题,在观看 fiddler 之后,我意识到从 webclient 到服务器的第一次调用不包含任何 cookie,所以我去掉了 CookieContainer 并替换它有了这个:

    WebClient e = new WebClient();
    e.Headers.Add(HttpRequestHeader.Cookie, "cookies I get from webbrowser control");

瞧,一切都很好!