簡體   English   中英

C#WebClient表單身份驗證

[英]C# WebClient FormsAuthentication

編輯:在底部。

我有一個使用WebService的站點。 使用以下方式啟用身份驗證:“ 如何:實現簡單表單身份驗證 ”。

我有一個WinForms應用程序,它無法連接到WebService(因為此程序需要身份驗證)。 有一個示例如何在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 is not嗎?我站在我的一邊,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服務器上配置的問題?

再次感謝社區!

好吧,我真的沒有找到答案。

我這樣做的方法是:使用“表單身份驗證”保護所有網頁。 但是不能保護我要使用的服務...(因為是的,這就是所有這些的目標!)

無論如何,非常感謝大家。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM