ASP.NET、C# 讀、寫 Session、Cookies

  • 10223
  • 0

ASP.NET、C# 讀、寫 Session、Cookies

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebPage1.aspx.cs" Inherits="WebPage1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br /><br />
        請輸入名字:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <asp:Button ID="btnLoginNPrint" runat="server" Text="登入" 
            onclick="btnLoginNPrint_Click" /> 
        <br /><br />
        <hr /><br /><br />
        登入的是:<asp:Label ID="lblUserName" runat="server" Text="?"></asp:Label>
        </div>
    </form>
</body>
</html>
using System;
using System.Web.UI;

public partial class TableMaintain_OU_WebPage1 : System.Web.UI.Page
{
    //屬性
    private string UserName
    {
        get
        {
            // Session轉String,若是null則轉成空白字串
            string sLoginName = Convert.ToString(Session["LoginName"] ?? "").Trim();

            if (sLoginName == string.Empty && Request.Cookies["LoginUser"] != null)
            {
                // 如果Cookie有登入紀錄,將之轉記到Session
                Session["LoginName"] = (string)Request.Cookies["LoginUser"]["Name"];
                // 讓cookie失效(逾期 = 將到期日設定為去年此時)
                Response.Cookies["LoginUser"].Expires = DateTime.Now.AddYears(-1);
            }
            return Convert.ToString(Session["LoginName"] ?? "").Trim();
        }
    }

    protected void btnLoginNPrint_Click(object sender, EventArgs e)
    {
        //登入 = 寫入Cookie(LoginUser這個Cookie的Name這個key值)
        Response.Cookies["LoginUser"]["Name"] = txtName.Text;

        // 未登入的話,就中止執行,並跳出訊息警示
        if (string.IsNullOrEmpty(this.UserName))
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID, "alert('您尚未登入或登入狀態已逾時,請重新登入');", true);
            return;
        }

        // 顯示登入者
        lblUserName.Text = this.UserName;
    }
}

進階閱讀:[ASP.net] Cookie怎麼寫就怎麼讀 https://dotblogs.com.tw/shadow/archive/2011/12/15/62306.aspx