Session的使用(登录例案+其它页面访问)

本程序功能是使用Session将用户输入的用户名保存在Session中(登录成功情况下,登录失败不会有Session值),其它页面想访问时会先判断是否有之前存的Session值。

登录Login.htm页面:

<head>
    <title></title>
    <script type="text/javascript">
        //刷新验证码
        function refreshYZM() {
            var imgYZM = document.getElementById("imgYZM");
            imgYZM.src = "YanZhengMa.ashx?t="+new Date();
        }
    </script>
</head>
<body>
    <form action="Login.ashx" method="post">
        <table>
            <tr><td>用户名</td><td><input type="text" name="username" /></td></tr>
            <tr><td>密码</td><td><input type="password" name="password" /></td></tr>
            <tr>
                <td>
                    <img src="YanZhengMa.ashx" id="imgYZM" onclick="refreshYZM()" />
                    </td><td><input type="text" name="yzm" />
                </td>
            </tr>
            <tr><td><input type="submit" name="btnLogin" value="登录" /></td><td>@msg</td></tr>
        </table>
    </form>
</body>
</html>

生成验证码YanZhengMa.ashx:

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "image/jpeg";
    Random rand = new Random();
    int num = rand.Next(1000, 10000);//生成4位随机数
    string code = num.ToString();
    context.Session[Login.YZM] = code;
    using (Bitmap bmp = new Bitmap(45, 25))
    {
        using (Graphics g = Graphics.FromImage(bmp))
        using (Font font = new Font(FontFamily.GenericSerif, 15))
        {
            g.DrawString(code, font, Brushes.Red, new PointF(0, 0));
        }
        bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
    }
}

登录Login.ashx页在(必须实现IRequiresSessionState接口,在using System.Data.SqlClient;命名空间下):

public const string YZM = "YZM";//存储验证码
public const string LOGINUSERNAME = "LoginUserName";//将登录用户名存到Session,供多个页面访问
public const string LOGINURL = "LoginUrl";//尝试登录的时候的页面地址

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/html";
    string btnLogin = context.Request["btnLogin"];//获取点击按钮
    string html = CommonHelper.ReadHtml("~/Login.htm");//获取Login.htm页面内容
    if (string.IsNullOrEmpty(btnLogin))//判断按钮是否点击
    {
        html = html.Replace("@msg", "");
        context.Response.Write(html);
    }
    else
    {
        string yzm = context.Request["yzm"];//获取用户输入的验证码
        string yzmInServer = (string)context.Session[YZM];//获取服务器的验证码
        if (yzm != yzmInServer)//判断用户输入与服务器的验证码
        {
            html = html.Replace("@msg","<font color=red>验证验错误</font>");
            context.Response.Write(html);
            return;
        }
        string username = context.Request["username"];
        string password = context.Request["password"];
        int r = (int)SQLHelper.ExecuteScalar("select count(*) from Users where name=@name and password=@password",
            new SqlParameter { ParameterName = "@name", Value = username },
            new SqlParameter { ParameterName = "@password", Value = password });
        if (r <= 0)
        {
            html = html.Replace("@msg", "<font color=red>用户名或密码错误</font>");
            context.Response.Write(html);
            return;
        }
        else
        {
            //如果登录成功
            context.Session[LOGINUSERNAME] = username;//把当前登录的用户名写到Session中
            //获取上一次访问网址的Session值,在QueryYuE.ashx和ChangePassword.ashx中已作判断,
            //当没登录时,就设置Session值"LOGINURL"为要访问的页面
            string navUrl = (string)context.Session[LOGINURL];
            if (navUrl != null)
            {
                context.Response.Redirect(navUrl);//重定向回到上一次访问的页面,动态获取
            }
            else
            {
                context.Response.Write("看,美丽的图片。。。。。");
            }
        }

    }
}

修改密码ChangePassword.ashx(须实现IRequiresSessionState):

public void ProcessRequest(HttpContext context)
{
    string username = (string)context.Session[Login.LOGINUSERNAME];//获取登录时存入的Session值
    if (username == null)//如果没登录强制性的访问此页面,则重定向到登陆页面
    {
        context.Session[Login.LOGINURL] = context.Request.Url.ToString();//把当前地址存到Session中
        context.Response.Redirect("Login.ashx");
    }
    else
    {
        context.Response.Write("修改密码。。。,当前登录用户<a href='Loginout.ashx'>退出登录</a>" + username);
    }
}

余额查询QueryYuE.ashx(须实现IRequiresSessionState):

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/html";
    string username = (string)context.Session[Login.LOGINUSERNAME];
    if (username == null)//如果没登录强制性的访问此页面,则重定向到登陆页面
    {
        context.Session[Login.LOGINURL] = context.Request.Url.ToString();//把当前地址存到Session中
        context.Response.Redirect("Login.ashx");
    }
    else
    {
        context.Response.Write("查询余额。。。,当前登录用户。<a href='Loginout.ashx'>退出登录</a>" + username);
    }
}

退出登录Loginout.ashx(须实现IRequiresSessionState):

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/html";
    context.Session.Abandon();//销毁Session
    context.Response.Redirect("Login.ashx");
}

帮助类CommonHelper.cs:

public class CommonHelper
{
    public static string ReadHtml(string path)
    {
        string fillPath = HttpContext.Current.Server.MapPath(path);
        string html = File.ReadAllText(fillPath);
        return html;
    }
}
原文地址:https://www.cnblogs.com/genesis/p/4684915.html