开发者

How do I log into a site with WebClient?

开发者 https://www.devze.com 2023-02-06 03:40 出处:网络
I want to do开发者_运维百科wnload something using a WebClient object in C#, but the download domain requires me to be logged in. How can I log in and keep session data using WebClient? I know how to p

I want to do开发者_运维百科wnload something using a WebClient object in C#, but the download domain requires me to be logged in. How can I log in and keep session data using WebClient? I know how to post data with WebClient.


If the problem you are having is you can authenticate but you cant keep the authentication cookie here is a cookie aware version of WebClient.

private class CookieAwareWebClient : WebClient
{
    public CookieAwareWebClient()
        : this(new CookieContainer())
    { }
    public CookieAwareWebClient(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;
    }
}

EDIT: The link you gave me uses forms authentication with HTTP POST, I don't have the time to walk though it but at least it gives you a start with Google.


Take a look at using the Credentials property. E.g. if Basic authentication is used, you will have to set the property to an instance of NetworkCredential with the proper username and password.

The sample pointed to shows how to use the currently logged on user credentials for the request.

0

精彩评论

暂无评论...
验证码 换一张
取 消