簡體   English   中英

將憑證發布到C#登錄頁面

[英]Posting Credentials To C# Login Page

我寫了一個測試登錄頁面(.aspx),它具有一個Postback方法和第二個靜態Webmethod調用。 javascript函數從“ txt1”和“ txt2”中獲取值,然后調用C#[WebMethod]

HTML:

<input type="text" id="txt1" />
<input type="text" id="txt2" />

//JS function sends values to C# WebMethod
PageMethods.ReceiveUsernamePassword(txt1.value, txt2.value);

C#:

    [WebMethod]
    public static string ReceiveUsernamePassword(string user, string pass)
    {
        File.AppendAllText(@"C:\Z\upjs.txt", user + " " + pass + " js " + "\r\n\r\n\r\n");
        return "Success JS";
    }

一個單獨的客戶端應用程序,使用以下代碼模擬POST。 URL指向localhost:1073 / PostData_Server / Default.aspx / ReceiveUsernamePassword:

using (WebClient client = new WebClient())
        {
            System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
            reqparm.Add("user", "user1");
            reqparm.Add("pass", "password1");
            byte[] responsebytes = client.UploadValues("http://local:1073/PostData_Server/Default.aspx", "POST", reqparm);
            string responsebody = Encoding.UTF8.GetString(responsebytes);
        }

Firebug POST數據

螢火蟲回應

我沒有在測試客戶端應用程序上獲取“成功”或“成功JS”,而是收到了整個HTML文檔作為響應消息。 同樣,沒有文本文件寫入服務器端。 我通過下標海報( https://addons.mozilla.org/en-us/firefox/addon/poster/ )來驗證這不是我的客戶端應用程序中的錯誤。 它也接收整個HTML文檔作為響應。 我該如何糾正?

只是以為我會在這個問題上更新我的發現。 事實證明,要調用[WebMethod],必須將ContentType設置為“ application / json”。 您也不能使用WebClient.UploadValues(),因為它不會讓您更改ContentType。 因此,為了發送正確的POST簽名,必須使用HttpWebRequest類。

另請注意:發送的用戶名和密碼必須為json格式!

    HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
    myHttpWebRequest.Method = "POST";
    myHttpWebRequest.ContentType = "application/json; encoding=utf-8";

    using (var streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()))
    {
        string json = "{user:\"user1\",pass:\"pass1\"}";

        streamWriter.Write(json);
        streamWriter.Flush();
    }

    var httpResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        responsebody = streamReader.ReadToEnd();
    }

暫無
暫無

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

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