C# WebClient FormsAuthentication

C# WebClient FormsAuthentication

编辑:在底部。

我的这个网站使用了 Web 服务。 使用这种方式启用身份验证: “How to: Implement Simple Forms Authentication”。

我有一个无法连接到 WebService 的 WinForms 应用程序(因为它需要身份验证)。 有一个如何在 WebService 和 WinForms 之间执行此身份验证的示例?我听说过 System.Net.HttpWebRequest,但我没有找到使用它的例子。

class CookieWebClient : WebClient
{
        public CookieContainer CookieContainer { get; private set; }

        /// <summary>
        /// This will instanciate an internal CookieContainer.
        /// </summary>
        public CookieWebClient()
        {
            this.CookieContainer = new CookieContainer();
        }

        /// <summary>
        /// Use this if you want to control the CookieContainer outside this class.
        /// </summary>
        public CookieWebClient(CookieContainer cookieContainer)
        {
            this.CookieContainer = cookieContainer;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address) as HttpWebRequest;
            if (request == null) return base.GetWebRequest(address);
            request.CookieContainer = CookieContainer;
            return request;
        }
}

当我想验证自己时:

using (var client = new CookieWebClient())
{
    var values = new NameValueCollection
    {
        { "UserEmail.Text", "Administrator" },
        { "UserPass.Text", "admin" },
    };
    client.UploadValues("http://localhost:54787/logon.aspx", values);

    // If the previous call succeeded we now have a valid authentication cookie
    // so we could download the protected page
    string result = client.DownloadString("http://localhost:54787/MyWantedPage.aspx");
}

问题可能是,我并没有真正在 Logon.aspx...(UserMail 和 UserPass)的正确字段中输入正确的用户名和密码 (Administrator/admin)。

你有什么事吗? (当然我假设使用 WebClient class.. 更容易) (如果我真的明白了,NetworkCredentials 仅适用于 Windows 身份验证,而 Basic Authenticaiton 不可用?我在我身边,FormsAuthentication - 与我提供的 URL 相同)

编辑:

好的,我看到这里了:

http://odetocode.com/articles/162.aspx

于是,我也尝试执行了在页面上看到的HTTPWebRequest。

关闭响应时出现此错误:

webRequest.GetResponse().Close();

错误如下:

System.Net.WebException: Le serveur distant a retourné une erreur : (500) Erreur interne du serveur.

à System.Net.HttpWebRequest.GetResponse()

显然我的 WebClient POST 请求和我的 HTTPWebRequest 确实有问题,可能需要在 IIS 服务器上进行配置?

再次感谢社区!

好的,我真的找不到答案。

我的做法是:使用表单身份验证保护所有网页。 但不保护我想消费的服务...(因为是的,这就是所有这一切的目标!)

非常感谢大家。