C# 如何使用WebClient登录网站?

C# 如何使用WebClient登录网站?,c#,login,webclient,C#,Login,Webclient,我想使用C#中的WebClient对象下载一些东西,但下载域要求我登录。如何使用WebClient登录并保存会话数据?我知道如何使用WebClient发布数据。如果您遇到的问题是您可以进行身份验证,但无法保留身份验证cookie,这里是支持cookie的WebClient版本 private class CookieAwareWebClient : WebClient { public CookieAwareWebClient() : this(new CookieCon

我想使用C#中的WebClient对象下载一些东西,但下载域要求我登录。如何使用WebClient登录并保存会话数据?我知道如何使用WebClient发布数据。

如果您遇到的问题是您可以进行身份验证,但无法保留身份验证cookie,这里是支持cookie的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;
    }
}
编辑: 你给我的链接使用HTTP POST的表单身份验证,我没有时间浏览它,但至少它让你从Google开始。

看看如何使用该属性。例如,如果使用基本身份验证,则必须使用正确的用户名和密码将属性设置为的实例


指向的说明如何使用当前登录的用户凭据进行请求。

服务器需要什么样的身份验证机制?Basic、Forms、Windows/NTLM?lol i通过从firefox cookies中查看添加值来解决问题:)webClient.Headers.Add(“Cookie”,“PHPSESSID=xxxxxxx;mosesuser=xxxxxxx;”;哪些价值观?你是说真正的认证cookie吗?请记住,该值可能会过期,以后无法重用。是的,我知道。因此,每当我运行该软件时,我都会通过firefox登录并复制粘贴cookie:)我发现了这个。但是我需要做什么呢?我必须通过httpwebrequest进行身份验证吗?这取决于您连接到的站点使用的身份验证系统。查看其他一些关于身份验证提示的回复我希望这篇文章能够包含一个关于实际身份验证过程本身的示例。@MonsterMMORPG中的答案有类似的解决方案,并且有一个示例使用代码。如果您在代码示例中包含了哪些名称空间,我会节省很多时间。这是非常重要的信息…好吧,我明白了。服务器使用表单身份验证。这要求您将用户名和密码发布到登录页面html中指定的操作url。您还必须使用cookie容器才能接收对该帖子的响应附带的身份验证cookie。@MonsterMMORPG
DoesNotWorkNullReferenceException