【问题标题】:C# WebClient FormsAuthenticationC# WebClient FormsAuthentication
【发布时间】:2023-04-11 03:31:01
【问题描述】:

编辑:在底部。

我有一个使用 WebService 的网站。 使用这种方式启用身份验证: “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)。

你在做什么? (当然我认为 WebClient 类更容易使用..) (如果我真的明白了,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 服务器上进行配置?

再次感谢社区!

【问题讨论】:

  • 那么您已经尝试过发送 HttpWebRequest 了吗?您是否尝试将 NetworkCredentials 添加到其 Credentials 属性?
  • @GrawCube 我已经厌倦了这个:(见编辑)
  • 好的,有人有答案吗? :D
  • 没人知道吗?

标签: c# httpwebrequest basic-authentication


【解决方案1】:

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

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

无论如何,非常感谢你们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 2014-08-26
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多