简单的Session登录

Login前台页面

    <form id="form1" action ="" method="post">
        <input type="text" name="txtN" />
        <input type="password" name="txtP" />
        <input type="submit" value="登陆" />
    </form>

 Login后台页面

 protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod.ToLower() == "post")
            {
                string strN = Request.Form["txtN"];
                string strP = Request.Form["txtP"];
                //登录成功
                if (strN == "admin" && strP == "123")
                {
                    //将用户名存入Session中
                    //Context.Session
                    Session["cname"] = strN;
                    //让浏览器重定向到首页
                    Response.Redirect("SessionIndex.aspx");
                }
            }
        }

 index后台页面

  protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["cname"] != null && !string.IsNullOrEmpty(Session["cname"].ToString()))
            {
                Response.Write("欢迎您登录~~:" + Session["cname"].ToString());
            }
            else
            {
                Response.Write("<script>alert('您还没有登录~~!');window.location='SessionLogin.aspx';</script>");
                Response.End();
            }
        }

 为了防止浏览器禁用Cookie时无法正常访问我们需要在Web.config中添加如下代码

//<system.web>添加如下代码,让浏览器能正常访问
      <sessionState cookieless="AutoDetect"></sessionState>
原文地址:https://www.cnblogs.com/mekor/p/3671946.html