首先,弄个基类

  1. /// <summary>
  2. /// 所有控制器基类,里面重写了OnActionExecuted方法
  3. /// </summary>
  4. public class BaseController : Controller
  5. {
  6.  
  7. /// <summary>
  8. /// 是否需要校验
  9. /// </summary>
  10. public bool IsCheckLogin { get; set; } = true;
  11.  
  12. /// <summary>
  13. /// 已登陆的用户信息
  14. /// </summary>
  15. public UserInfo LoginUser { get; set; }
  16.  
  17. /// <summary>
  18. /// 在方法执行之前调用
  19. /// </summary>
  20. /// <param name="filterContext"></param>
  21. protected override void OnActionExecuting(ActionExecutingContext filterContext)
  22. {
  23. base.OnActionExecuting(filterContext);
  24.  
  25. //如果页面需要校验
  26.  
  27. if (IsCheckLogin)
  28. {
  29. #region Session方式
  30. ////校验用户是否登陆
  31. //if (filterContext.HttpContext.Session["LoginUser"] == null)
  32. //{
  33. // //为空,则跳转到登陆
  34. // filterContext.HttpContext.Response.Redirect("/UserLogin/Index");
  35.  
  36. //}
  37. //else
  38. //{
  39. // //不为空,则将用户登陆信息存储
  40. // LoginUser = filterContext.HttpContext.Session["LoginUser"] as UserInfo;
  41. // //将信息存入viewBag中
  42. // ViewBag.UserInfo = LoginUser;
  43. //}
  44. #endregion
  45.  
  46. #region 缓存方式
  47. //校验用户是否登陆
  48. //获取cookie中的信息
  49.  
  50. if (Request.Cookies["userLoginGuid"] == null)
  51. {
  52. //为空,则跳转到登陆
  53. filterContext.HttpContext.Response.Redirect("/UserLogin/Index");
  54. return;
  55. }
  56. string guidUser = Request.Cookies["userLoginGuid"].Value;
  57. UserInfo userInfo = CacheHelper.getCache<UserInfo>(guidUser);
  58. if (userInfo == null)
  59. {
  60. //用户长时间不操作,超时
  61. filterContext.HttpContext.Response.Redirect("/UserLogin/Index");
  62. return;
  63. }
  64.  
  65. //不为空,则将用户登陆信息存储
  66. LoginUser = userInfo;
  67. //将信息存入viewBag中
  68. if (LoginUser == null)
  69. {
  70. ViewBag.UserInfo = "";
  71. }
  72. else
  73. {
  74. ViewBag.UserInfo = LoginUser;
  75. }
  76.  
  77. //滑动窗口机制
  78. CacheHelper.SetCache(guidUser, userInfo, DateTime.Now.AddMinutes());
  79. #endregion
  80.  
  81. }
  82. }
  83.  
  84. }

,这个基类中有两个属性,

一个是IsCheckLogin,默认为true,该属性主要在子类的构造函数中进行初始化,确定子类是否需要进行登陆认证,一般登陆控制器应设为false

一个是LoginUser,主要记录当前登陆成功用户的实体类

在重写OnActionExecuting的方法中,首先校验IsCheckLogin是否为true,如是,则说明需要登陆校验

此时从cookie中找到登陆时随机生成的guid码,如果没有找到,则直接返回到登陆界面

如果找到,则依据此guid码从缓存中寻找对应的用户实体,如果没有找到一样返回登陆界面,

如果找到则将用户实体放入LoginUser中,以便子类需要.

最后设置缓存的过期时间

其中还用到缓存,缓存类的代码如下

  1. public interface ICacheWrite
  2. {
  3. bool AddCache(string key, object value);
  4. bool AddCache(string key, object value, DateTime exprity);
  5. object GetCache(string key);
  6. T getCache<T>(string key);
  7.  
  8. void SetCache(string key, object value, DateTime exprity);
  9. void SetCache(string key, object value);
  10. }

缓存的接口类

  1. public class HttpRuntimeCacheWriter : ICacheWrite
  2. {
  3. public bool AddCache(string key, object value)
  4. {
  5. HttpRuntime.Cache.Insert(key, value);
  6. return true;
  7. }
  8.  
  9. public bool AddCache(string key, object value, DateTime exprity)
  10. {
  11. HttpRuntime.Cache.Insert(key, value, null, exprity, TimeSpan.Zero);
  12. return true;
  13. }
  14.  
  15. public object GetCache(string key)
  16. {
  17. return HttpRuntime.Cache.Get(key);
  18. }
  19.  
  20. public T getCache<T>(string key)
  21. {
  22. return (T)HttpRuntime.Cache[key];
  23. }
  24.  
  25. public void SetCache(string key, object value)
  26. {
  27. HttpRuntime.Cache.Remove(key);
  28. AddCache(key, value);
  29. }
  30.  
  31. public void SetCache(string key, object value, DateTime exprity)
  32. {
  33. throw new NotImplementedException();
  34. }
  35.  
  36. }

运用HttpRuntime缓存

  1. public class CacheHelper
  2. {
  3. //这里应该用注入,因为可能更改为其它实现了ICacheWrite的对象
  4. public static ICacheWrite write { get; set; } = new HttpRuntimeCacheWriter(); //new MemcacheWriter();
  5.  
  6. public static bool AddCache(string key, object value)
  7. {
  8. return write.AddCache(key, value);
  9. }
  10.  
  11. public static bool AddCache(string key, object value, DateTime exprity)
  12. {
  13. return write.AddCache(key, value, exprity);
  14. }
  15.  
  16. public static object GetCache(string key)
  17. {
  18. return write.GetCache(key);
  19. }
  20.  
  21. public static T getCache<T>(string key)
  22. {
  23. return write.getCache<T>(key);
  24. }
  25.  
  26. public static void SetCache(string key, object value)
  27. {
  28. write.SetCache(key, value);
  29. }
  30.  
  31. public static void SetCache(string key, object value, DateTime exprity)
  32. {
  33. write.SetCache(key, value, exprity);
  34. }
  35. }

缓存帮助类

然后前台调用示例

  1. public class LoginController : BaseController
  2. {
  3. //得到用户服务层对象
  4. IUserInfoSerivce userSerivce = new UserInfoSerivce();
  5.  
  6. public LoginController()
  7. {
  8. this.IsCheckLogin = false;
  9. }
  10. // GET: Login
  11. public ActionResult Login()
  12. {
  13.  
  14. return View();
  15. }
  16.  
  17. /// <summary>
  18. /// 进行简单登陆检验
  19. /// </summary>
  20. /// <param name="uid"></param>
  21. /// <param name="pwd"></param>
  22. /// <returns></returns>
  23. public ActionResult Check(string uid,string pwd)
  24. {
  25. if (!Checked(uid,pwd))
  26. {
  27. var user = userSerivce.GetEntities(u => u.Uid == uid && u.pwd == pwd).FirstOrDefault();
  28. if (user!=null)
  29. {
  30. //立即分配一个标志,Guid,把标志作为key(并写入cookie中),把用户放到value中
  31. string userLoginGuid = Guid.NewGuid().ToString();
  32. Response.Cookies["userLoginGuid"].Value = userLoginGuid;
  33. //将用户登陆信息存到缓存中
  34. CacheHelper.AddCache(userLoginGuid, user, DateTime.Now.AddMinutes());
  35. return Content("ok");
  36. }
  37. }
  38. return Content("ok");
  39. }
  40.  
  41. /// <summary>
  42. /// 检查用户名密码是否正确
  43. /// </summary>
  44. /// <param name="uid"></param>
  45. /// <param name="pwd"></param>
  46. /// <returns></returns>
  47. private bool Checked(string uid,string pwd)
  48. {
  49. bool reslut = string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(pwd);
  50. return reslut;
  51. }
  52. }

其它控制器只用继承基类即可

  1. public class DefaultController : BaseController
  2. {
  3. IBLL.IFriendInfoSerivce friendSerivce = new BLL.FriendInfoSerivce();
  4. // GET: Default
  5. public ActionResult Index()
  6. {
  7. ViewData.Model = friendSerivce.GetEntities(f => !f.DelFlag);
  8. return View();
  9. }
  10. }

粗略画个图表示下

MVC登陆认证简单设置的更多相关文章

  1. 【配置】检测到在集成的托管管道模式下不适用的ASP.NET设置的解决方法(非简单设置为【经典】模式)。

      ×   检测到在集成的托管管道模式下不适用的ASP.NET设置的解决方法(非简单设置为[经典]模式). 我们将ASP.NET程序从IIS6移植到IIS7,可能运行提示以下错误: HTTP 错误 5 ...

  2. Spring Boot确保Web应用安全(登陆认证)

    Spring Boot官方提供了一个登陆认证的清晰易懂的 例子 , 我们在次以此例展开演示Spring Boot是如何实现登陆认证的. 首先我们去 https://start.spring.io/ 下 ...

  3. 批量实现SSH无密码登陆认证脚本

    批量实现SSH无密码登陆认证脚本 问题背景 使用为了让linux之间使用ssh不需要密码,可以采用了数字签名RSA或者DSA来完成.主要使用ssh-key-gen实现. 1.通过 ssh-key-ge ...

  4. 批量SSH key-gen无密码登陆认证脚本 附件脚本

    # 批量实现SSH无密码登陆认证脚本 ## 问题背景 使用为了让linux之间使用ssh不需要密码,可以采用了数字签名RSA或者DSA来完成.主要使用ssh-key-gen实现. 1.通过 ssh-k ...

  5. ASP.NET MVC 3 入门级常用设置、技巧和报错

    1.ASP.NET MVC 3 如何去除默认验证 这个默认验证是在web.config配置文件中设置的    <add key="ClientValidationEnabled&quo ...

  6. spring-security 登陆认证之初次探究

    首先,希望还对 spring-security框架完全不懂的新手 下载下Git源码. 引入到项目中.这个短文就是边看源码边聊的.也会启动下项目验证自己的推想. 一.登陆认证的登陆配置项 <for ...

  7. 使用TT模板+mvc+wcf实现简单查询

    今天是除夕,小编的这篇博客是掐着点儿发的,在此,祝各位小伙伴新年快乐,身体健康,万事如意:喜从天降,欣喜若狂:喜气盈门,好事成双:好人好运,金玉满堂:神采飞扬,如愿以偿,财源滚滚来,福如东海长:伴随着 ...

  8. Spring集成shiro做登陆认证

    一.背景 其实很早的时候,就在项目中有使用到shiro做登陆认证,直到今天才又想起来这茬,自己抽空搭了一个spring+springmvc+mybatis和shiro进行集成的种子项目,当然里面还有很 ...

  9. {Django基础九之中间件} 一 前戏 二 中间件介绍 三 自定义中间件 四 中间件的执行流程 五 中间件版登陆认证

    Django基础九之中间件 本节目录 一 前戏 二 中间件介绍 三 自定义中间件 四 中间件的执行流程 五 中间件版登陆认证 六 xxx 七 xxx 八 xxx 一 前戏 我们在前面的课程中已经学会了 ...

随机推荐

  1. springboot-登录拦截器

    小伙伴们大家好,今天给大家分享一个简单的springboot版登录拦截器 首先我们需要在springboot的启动类中让它实现WebMvcConfigurer 这个接口 比如: public clas ...

  2. 使用原生方法从kafka消费消息

    kafka最早是linkedin开发的一套高性能类队列结构,具有发布—订阅功能.现在是apache的项目之一.支持很多种客户端从其中进行consume,网上也有许多第三方的客户端(注1),但下面我们只 ...

  3. Python replace方法的使用

    在Python str 中, 有一个很方便的查找替换的函数 replace() my_str = "lowmanmana" new_str = my_str.replace(&qu ...

  4. PARSER_JS_PRECISION_RANGE_EXCEEDED 错误

    { [Error: parseLengthCodedNumber: JS precision range exceeded, number is >= 53 bit: "3037620 ...

  5. jmeter报错

    1.检测服务性能是报超时时问题 解决:因为服务器限制只能域名访问不能用ip+端口访问,但是jmter使用的是IP+端口访问 如图: 所以需要服务器放开这个端口,改成可以使用这个IP+端口访问

  6. Adapter as a WCF Binding - In Depth

    WCF LOB Adapter SDK surfaces an adapter as a custom WCF Binding.  A WCF Bindingcorresponds to the “H ...

  7. yii2之ActiveForm表单使用

    因目前项目并非前后端分离模式,且用到PHP的yii2框架(所有html代码,js较多内嵌在.php文件内多少采用同步提交[喷墨中...]),遂对于前端面上需要用到的yii2小组件一些整理(因是前端若涉 ...

  8. (转)用Python写堡垒机项目

    原文:https://blog.csdn.net/ywq935/article/details/78816860 前言 堡垒机是一种运维安全审计系统.主要的功能是对运维人员的运维操作进行审计和权限控制 ...

  9. C#设计模式系列目录

    http://www.cnblogs.com/libingql/archive/2012/04/16/2451608.html 抽空,学习,加强!

  10. SQL中存储过程和函数的区别

    转:https://www.cnblogs.com/jacketlin/p/7874009.html 本质上没区别.只是函数有如:只能返回一个变量的限制.而存储过程可以返回多个. 而函数是可以嵌入在s ...