2013年9月23日 星期一

如何在 .aspx 將資料 post 到 .ashx

最近小弟要做一個活動頁面,此頁面是投票活動,要綁會員投票資訊,但是未登入者也可以觀看此頁面。

使用者給我的介面有兩個步驟完成投票,第一個步驟有兩個區塊,一個是即時登入頁面,一個是即時註冊頁面;第二個步驟是投票選項,這兩個步驟都選定了才能將資料送出。

附帶條件是不能利用連結導向到登入頁面和註冊頁面,因為怕瀏覽者點走了就不知道怎麼回來,所以只能在當頁將所有動作完成。

遇到這個狀況,我想說如果使用 ajax 送出資料到另一個頁面去註冊或者做登入,那成功或錯誤訊息送回來,我要怎麼將傳回來的 MemberID 存起來,隱藏欄位?cookie?最後決定使用 post 到 ashx 再將 MemberID 傳回來,再將傳回來的資料存在session內,繼續做投票動作。

於是 我參考了 [ASP.NET]在server端post資料到.ashx 內的程式碼來解決問題。

LoginHander.ashx.cs
public class LoginHandler : IHttpHandler, IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        string strID = string.Empty;
        string strMsg = string.Empty;
        string strEMail = context.Request.Form["Email"];
        string strPassword = context.Request.Form["Password"];

        if (string.IsNullOrEmpty(strEMail))
        {
            strMsg += (strMsg == string.Empty) ? "Please input email address.<br/>" : "";
        }

        if (string.IsNullOrEmpty(strPassword))
        {
            strMsg += (strMsg == string.Empty) ? "Please input password.<br/>" : "";
        }
        
        //建立會員資料查詢物件
       
        string msg;

        bool isSuccess = /* 檢查帳密是否正確 */
        if (!isSuccess)
        {
            strMsg += (strMsg == string.Empty) ? "Sorry, unrecognized email address or password.<br/>" : "";
        }

  /* 額外判斷 */
  
  strID = /* 取得會員ID */
  
        if (string.IsNullOrWhiteSpace(strMsg))
        {
            context.Response.Write("true," + strID);

        }
        else
            context.Response.Write(strMsg);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

.aspx.cs 中的按鈕
protected void btnSubmitLogin_Click(object sender, EventArgs e)
{
    lblLoginErrorMessage.Text = string.Empty;
    var url = "http://www.sample.com/../../LoginHandler.ashx"; // 網址路徑 

    WebRequest request = WebRequest.Create(url);
    request.Method = "POST";

    // server 端可以透過 Request.Form["Email"] 和 Request.Form["Password"] 讀取
    string postData = string.Format("Email={0}&Password={1}", txtEMail.Text, txtPassword.Text);

    byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    request.ContentType = "application/x-www-form-urlencoded";

    // Set the ContentLength property of the WebRequest.
    request.ContentLength = byteArray.Length;

    // Get the request stream.
    using (Stream dataStream = request.GetRequestStream())
    {
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
    }

    // Get the response.      
    using (WebResponse response = request.GetResponse())
    {
        using (Stream dataStream = response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(dataStream))
            {
                string responseFromServer = reader.ReadToEnd();
    
    /* 回傳資料若開頭為 true */
                if (responseFromServer.Trim().StartsWith("true"))
                {
     /* 紀錄 ID */
                    Session["MemberID"] = responseFromServer.Trim().Replace("true,", "");

     /* 後續資料處理 */
                }
                else
                {
     /* 錯誤訊息顯示 */
                    lblLoginErrorMessage.Text = responseFromServer.Trim();
                }
            }
        }
    }
}





沒有留言 :

張貼留言

Related Posts Plugin for WordPress, Blogger...