C#Winforms Application和FormsAuthentication

时间:2015-03-17 14:05:17

标签: c# forms-authentication webclient

我有一个WinForms应用程序(只有一个试图获取Default.aspx页面的按钮)和一个带有FormsAuthentication(Logon.aspx和Default.aspx)的WebSite

这是我的两个代码:

https://www.dropbox.com/s/40qib4a9gynrs00/test.zip?dl=0

我试图使用CookieContainer类来验证我自己的网站......但它不起作用......

你能查看我错在哪里吗?我的意思是,我已经有5天了......我真的找不到答案。谢谢!

编辑:

我有我的部分代码,但不起作用:

        private void button1_Click(object sender, EventArgs e)
    {
        using (var client = new CookieWebClient())
        {
            var values = new NameValueCollection { { "user", "admin" }, { "password", "cool" } };

            string result1 = client.DownloadString("http://localhost:49689/Default.aspx"); //result1  : Redirect to Logon.aspx
            client.UploadValues("http://localhost:49689/Logon.aspx", values);
            string result = client.DownloadString(new Uri("http://localhost:49689/Default.aspx"));
            MessageBox.Show(result); //All the DefaultPage (if that works), but of course it doesnt works...
        }
    }

在结果字符串上,您可以看到重定向到Logon.aspx,因为身份验证不起作用。请帮助^^!

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码控制WebBrowser组件的登录:

    private void button1_Click(object sender, EventArgs e)
    {
        var wb = new WebBrowser
        {
            ScriptErrorsSuppressed = true
        };

        wb.Navigate("http://localhost:49689/Logon.aspx");
        while (wb.ReadyState != WebBrowserReadyState.Complete)
            Application.DoEvents();

        wb.Document.GetElementById("user").InnerText = "admin";
        wb.Document.GetElementById("password").InnerText = "cool";
        wb.Document.GetElementById("Submit1").InvokeMember("click");

        wb.DocumentCompleted += wb_DocumentCompleted;

        while (!completed)
            Application.DoEvents();

        var resultHeader = wb.Document.Url.OriginalString;
        var result = wb.Document.Body.InnerHtml;

        var cookie = wb.Document.Cookie;
        MessageBox.Show(cookie, "Cookie");
        MessageBox.Show(result, resultHeader);
    }

    private bool completed;
    private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        completed = true;
        ((WebBrowser)sender).DocumentCompleted -= wb_DocumentCompleted;
    }

编辑1:
    - 添加了获取cookie