Asp.Net WebForm 完美登录的两种方法


两种方法的共同部分
在根目录下新建Default.aspx,Login.aspx,登陆模板使用的是网上随意找的,当然也可以不用的其实。
前台代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login_.aspx.cs" Inherits="完美登陆.Login" %>

<!DOCTYPE html>
<html>
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>后台登录</title>
    <link href="Scripts/css/login.css" rel="stylesheet" />
    <script src="Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
    //这里有两个用处:第一、点击验证码刷新一次,
    //第二、在一般处理程序后面加些冗余的数据避免浏览器直接从缓存中拿到原来的验证码
        $(function () {
            $("#Image").click(function () {
                var oldSrc = $(this).attr("src");
                oldSrc += new Date().toString("yyyy-MM-dd HH:mm:ss");
                $(this).attr("src", oldSrc);
            })
        });
    </script>
</head>
<body>

    <div class="login">
        <div class="message">登录</div>
        <div id="darkbannerwrap"></div>

        <form id="form1" runat="server">
            <input name="action" value="login" type="hidden">
            <input name="username" placeholder="用户名" required="" type="text">
            <hr class="hr15">
            <input name="password" placeholder="密码" required="" type="password">
            <hr class="hr15">
            <input name="VCode" placeholder="验证码" required="" type="text" style="50%;height:40px">&nbsp;&nbsp;<img id="Image" src="Public/Common/ValideCode.ashx?id=1"/>
            <hr class="hr15">
            <input value="登录" style=" 100%;" type="submit">
            <hr class="hr20">
        </form>
    </div>
</body>
</html>

后置代码类

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        string Name = Request["username"];
        string password = Request["password"];
        string VCode = Request["VCode"];
        //在验证码处理程序中,将验证码放入Session中(一般处理程序虚要实现标记接口IRequiresSessionState)
        if (VCode == Session["ValidateCode"].ToString())
        {
            if (Name == "xuxuzhaozhao1" && password == "XXXX")
            {
                //X分别填写下面两种方法不同的代码
                X
            }
        }
        else
        {
            Response.Write("<script>alert('验证码错误')</script>");
        }
    }
}

第一种方法:
这种方法比较简单,是我从某个教学视频上看来得,感觉还阔以。

其核心思想是,在登录校验成功后,将该用户放入Session["User"]中,然后在每个需要登录后才能访问的页面中判断Session["User"]是否为空,如果为空在跳转到登陆页面,当然好的程序员是不会让相同的代码多次出现的。
基于所有的webform都继承自System.Web.UI.Page,所以我们要做的就是新建一个BasePage,让BasePage来继承System.Web.UI.Page,然后其他的webform来继承BasePage
1、BasePage.cs

//所有页面初始化的时候都要执行BasePage的Page_Init方法
//Page_Load执行之前会先去执行Page_Init方法
protected virtual void Page_Init(object sender, EventArgs e)
{
    if (Session["User"] == null)
    {
        Response.Redirect("~/Login.aspx");
        return;
    }
}

2、在登录页面的X处填写以下代码

Session["User"] = UserModel;
Response.Redirect("~/Default.aspx")

这个方法呢,我暂时还不知道怎样验证后返回请求页面,只能写死到默认页面,希望哪个有缘人知道的不吝赐教。

第二种方法:
哎,这种方法就很舒服了。跟上篇那个MVC身份验证相同

1、配置根目录下的Web.config加入节点

<system.web>
    <authentication mode="Forms">
        <forms loginUrl="Login_.aspx"></forms>
    </authentication>
    <authorization>
        <deny users="?"/>
    </authorization>
</system.web>

2、在项目中放入新建一个Public文件夹,这里存放不需要身份验证就能访问的页面或处理程序如:注册页面,验证码生成处理程序。在Public文件夹下加入Web.config文件,不要问我为什么有两个Web.config,反正县官不如现管,Web.config加入以下xml代码

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</configuration>

3、在X处填写以下代码

//将经过身份验证的用户重定向回最初请求的 URL或者Default.aspx。
FormsAuthentication.RedirectFromLoginPage(xxxName, true);

一旦登录成功后,可以在其他任意页面获取登录者的姓名xxxName

<%if(User.Identity.IsAuthenticated){%>
    <b><%= User.Identity.Name%></b>
<%}%>

此处是福利!!!!
验证码生成类(可以直接拷贝使用)

ValidateCode.cs

//=================================================
//                                                                *
// 作 者:xuxuzhaozhao
// 邮 箱:xuxuzhaozhao@icloud.com
// 博 客:http://www.cnblogs.com/xuxuzhaozhao/
// 时 间:2017年3月18日 15:48:51
// 描 述:验证码生成类,配合一个验证码一般处理程序一起使用 
//                                                                *
//=================================================

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

namespace 完美登陆.Public.Common
{
    /// <summary>
    ///生成验证码
    /// </summary>
    public class ValidateCode
    {
        public ValidateCode()
        {
        }
        /// <summary>
        /// 验证码的最大长度
        /// </summary>
        public int MaxLength
        {
            get { return 10; }
        }
        /// <summary>
        /// 验证码的最小长度
        /// </summary>
        public int MinLength
        {
            get { return 1; }
        }
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="length">指定验证码的长度</param>
        /// <returns></returns>
        public static string CreateValidateCode(int length)
        {
            int[] randMembers = new int[length];
            int[] validateNums = new int[length];
            string validateNumberStr = "";
            //生成起始序列值
            int seekSeek = unchecked((int)DateTime.Now.Ticks);
            Random seekRand = new Random(seekSeek);
            int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);
            int[] seeks = new int[length];
            for (int i = 0; i < length; i++)
            {
                beginSeek += 10000;
                seeks[i] = beginSeek;
            }
            //生成随机数字
            for (int i = 0; i < length; i++)
            {
                Random rand = new Random(seeks[i]);
                int pownum = 1 * (int)Math.Pow(10, length);
                randMembers[i] = rand.Next(pownum, Int32.MaxValue);
            }
            //抽取随机数字
            for (int i = 0; i < length; i++)
            {
                string numStr = randMembers[i].ToString();
                int numLength = numStr.Length;
                Random rand = new Random();
                int numPosition = rand.Next(0, numLength - 1);
                validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
            }
            //生成验证码
            for (int i = 0; i < length; i++)
            {
                validateNumberStr += validateNums[i].ToString();
            }
            return validateNumberStr;
        }
        /// <summary>
        /// 创建验证码的图片,把验证码写到响应流中去
        /// </summary>
        /// <param name="containsPage">要输出到的page对象</param>
        /// <param name="validateNum">验证码</param>
        public static void CreateValidateGraphic(string validateCode,HttpContext context)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的干扰线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new Font("monaco", 12, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 2);
                //画图片的前景干扰点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //保存图片数据
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                context.Response.Clear();
                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite(stream.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        /// <summary>
        /// 得到验证码图片的长度
        /// </summary>
        /// <param name="validateNumLength">验证码的长度</param>
        /// <returns></returns>
        public static int GetImageWidth(int validateNumLength)
        {
            return (int)(validateNumLength * 12.0);
        }
        /// <summary>
        /// 得到验证码的高度
        /// </summary>
        /// <returns></returns>
        public static double GetImageHeight()
        {
            return 22.5;
        }
    }
}


原文地址:https://www.cnblogs.com/xuxuzhaozhao/p/6574481.html