Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 615|回复: 0

.Net Mvc判断用户是否登陆、未登陆跳回登陆页、三种完美解决方案

[复制链接]
  • TA的每日心情
    奋斗
    2024-9-22 15:19
  • 签到天数: 795 天

    [LV.10]以坛为家III

    2050

    主题

    2108

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    724084
    发表于 2021-6-9 03:43:23 | 显示全部楼层 |阅读模式

      开篇先不讲解,如何判断用户是否登陆,我们先来看用户登录的部分代码,账户密码都正确后,先将当前登录的用户名记录下来。

     1         public ActionResult ProcessLogin()
     2         {
     3             try
     4             {
     5                 string user_name = Request["LoginId"];
     6                 string user_pwd = Request["LoginPwd"];
     7                 UserInfo model = new UserInfo();
     8                 model.UName = user_name;
     9                 model.UPwd = user_pwd;
    10                 if (bllSession.UserInfo.Select(model).Count > 0) //判断用户名密码是否正确
    11                 {
    12                     Session["loginUser"] = user_name; //记录当前登录的用户名
    13                     return Content("ok");
    14                 }
    15                 else
    16                 {
    17                     return Content("用户名或密码错误!你会登陆吗?");
    18                 }
    19             }
    20             catch (Exception ex)
    21             {
    22                 throw ex;
    23             }
    24         }

    下面开始演示校验用户登录几种方式

    方式一

      在每个页面执行前判断当前用户是否登陆,若登陆才可以进入当前页面,没有登陆则跳回首页,网站页面少的话,可以在每个页面上添加此方法,随着项目模块越来越多,你还会想怎么复制粘贴嘛?Don't repeat youself!

    1         public ActionResult Index()
    2         {
    3             if (Session["loginUser"] == null)
    4             {
    5                 return RedirectToAction("Index", "UserLogin");
    6             }
    7             return View();
    8         }

    方式二

      全局过滤器中校验用户是否登陆

    创建一个校验类(LoginCheckFilterAttribute.cs)

     1 using System.Web.Mvc;
     2 
     3 namespace Sam.OA.WEBAPP.Models
     4 {
     5     /// <summary>
     6     /// 校验用户是否登陆帮助类
     7     /// </summary>
     8     public class LoginCheckFilterAttribute: ActionFilterAttribute  //注意继承:ActionFilterAttribute
     9     {
    10         /// <summary>
    11         /// 是否校验,默认为true
    12         /// </summary>
    13         public bool IsChecked { get; set; }
    14         public override void OnActionExecuted(ActionExecutedContext filterContext)
    15         {
    16             base.OnActionExecuted(filterContext);
    17             //校验用户是否已登录
    18             if (IsChecked)
    19             {
    20                 if (filterContext.HttpContext.Session["loginUser"] == null)
    21                 {
    22                     filterContext.HttpContext.Response.Redirect("/UserLogin/Index");
    23                 }
    24             }
    25         }
    26     }
    27 }

    在全局过滤器中添加这方法(FilterConfig.cs)

     1 using Sam.OA.WEBAPP.Models;
     2 using System.Web.Mvc;
     3 
     4 namespace Sam.OA.WEBAPP
     5 {
     6     public class FilterConfig
     7     {
     8         public static void RegisterGlobalFilters(GlobalFilterCollection filters)
     9         {
    10             //filters.Add(new HandleErrorAttribute());
    11             filters.Add(new MyExceptionFilterAttribute()); //自定义的过滤规则
    12 
    13             //校验用户是否登陆,默认为校验
    14             filters.Add(new LoginCheckFilterAttribute() { IsChecked=true});
    15         }
    16     }
    17 }

    这样一来 ,所有的页面都会校验用户是否登陆,可实际中偏偏有些地方是不需要校验用户是否登陆的,比如:登陆页面,此时我们如何解决这个问题呢?我们可以给类打上标签

    用户登录控制器(UserLoginController.cs)

     1 using Sam.OA.BLLFactory;
     2 using Sam.OA.Model.Sam;
     3 using Sam.OA.WEBAPP.Models;
     4 using System;
     5 using System.Web.Mvc;
     6 
     7 namespace Sam.OA.WEBAPP.Controllers
     8 {
     9     /// <summary>
    10     /// 打上标签,不校验用户是否登陆
    11     /// </summary>
    12     [LoginCheckFilterAttribute(IsChecked =false)] 13     public class UserLoginController : Controller
    14     {
    15         // GET: UserLogin
    16         public ActionResult Index()
    17         {
    18             return View();
    19         }
    20         IBllSession bllSession = BllSessionFactory.GetCurrentBllSession();
    21         /// <summary>
    22         /// 处理登陆的表单
    23         /// </summary>
    24         /// <returns></returns>
    25         public ActionResult ProcessLogin()
    26         {
    27             try
    28             {
    29                 string user_name = Request["LoginId"];
    30                 string user_pwd = Request["LoginPwd"];
    31                 UserInfo model = new UserInfo();
    32                 model.UName = user_name;
    33                 model.UPwd = user_pwd;
    34                 if (bllSession.UserInfo.Select(model).Count > 0) //判断用户名密码是否正确
    35                 {
    36                     Session["loginUser"] = user_name;
    37                     return Content("ok");
    38                 }
    39                 else
    40                 {
    41                     return Content("用户名或密码错误!你会登陆吗?");
    42                 }
    43             }
    44             catch (Exception ex)
    45             {
    46                 throw ex;
    47             }
    48         }
    49     }
    50 }

    这样一来问题完美的解决了,不需要校验用户是否登陆的地方打上标签~~~~

    方式三

    手动创建一个控制器基类(BaseController.cs)

     1 using System.Web.Mvc;
     2 
     3 namespace Sam.OA.WEBAPP.Controllers
     4 {
     5     /// <summary>
     6     /// 控制器基类帮助类
     7     /// 作者:陈彦斌
     8     /// 时间:2019年8月22日23:53:35
     9     /// </summary>
    10     public class BaseController:Controller
    11     {
    12         public bool IsCheckedUserLogin = true;
    13         protected override void OnActionExecuted(ActionExecutedContext filterContext)
    14         {
    15             base.OnActionExecuted(filterContext);
    16             //校验用户是否已登录
    17             if (IsCheckedUserLogin )
    18             {
    19                 if (filterContext.HttpContext.Session["loginUser"] == null)
    20                 {
    21                     filterContext.HttpContext.Response.Redirect("/UserLogin/Index");
    22                 }
    23             }
    24         }
    25     }
    26 }

    此时,我们需要做校验的控制器全部改写成继承控制器基类

     1 using Sam.OA.BLLFactory;
     2 using Sam.OA.Model.Sam;
     3 using System.Web.Mvc;
     4 
     5 namespace Sam.OA.WEBAPP.Controllers
     6 {
     7     /// <summary>
     8     /// 从继承:Controller改为继承基类:BaseController
     9     /// </summary>
    10     public class UserInfoController : BaseController //:Controller 
    11     {
    12         // GET: UserInfo
    13         IBllSession bll = BllSessionFactory.GetCurrentBllSession();
    14         public ActionResult Index()
    15         {
    16             UserInfo model = new UserInfo();
    17             ViewData.Model = bll.UserInfo.Select(model,"1=1");
    18             return View();
    19         }
    20         public ActionResult Create()
    21         {
    22             return View();
    23         }
    24         [HttpPost]
    25         public ActionResult Create(UserInfo model)
    26         {
    27             if (ModelState.IsValid)
    28             {
    29                 bll.UserInfo.Add(model);
    30             }
    31             return RedirectToAction("Index");
    32         }
    33     }
    34 }

    那么问题又来了,有些页面不校验如何做呢?要么不继承基类,要么按照下面方法配置,是不是感觉很灵活嘞

     1 using Sam.OA.BLLFactory;
     2 using Sam.OA.Model.Sam;
     3 using System;
     4 using System.Web.Mvc;
     5 
     6 namespace Sam.OA.WEBAPP.Controllers
     7 {
     8     public class UserLoginController :BaseController //:Controller
     9     {
    10         public UserLoginController()
    11         {
    12             this.IsCheckedUserLogin = false; //不校验用户是否登陆
    13         }
    14         // GET: UserLogin
    15         public ActionResult Index()
    16         {
    17             return View();
    18         }
    19         IBllSession bllSession = BllSessionFactory.GetCurrentBllSession();
    20         /// <summary>
    21         /// 处理登陆的表单
    22         /// </summary>
    23         /// <returns></returns>
    24         public ActionResult ProcessLogin()
    25         {
    26             try
    27             {
    28                 string user_name = Request["LoginId"];
    29                 string user_pwd = Request["LoginPwd"];
    30                 UserInfo model = new UserInfo();
    31                 model.UName = user_name;
    32                 model.UPwd = user_pwd;
    33                 if (bllSession.UserInfo.Select(model).Count > 0) //判断用户名密码是否正确
    34                 {
    35                     Session["loginUser"] = user_name;
    36                     return Content("ok");
    37                 }
    38                 else
    39                 {
    40                     return Content("用户名或密码错误!你会登陆吗?");
    41                 }
    42             }
    43             catch (Exception ex)
    44             {
    45                 throw ex;
    46             }
    47         }
    48     }
    49 }

    以上所有问题都已经完美解决~

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-10-5 14:15 , Processed in 0.061207 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表