话说来到上海已经快半年了,时光如白驹过隙,稍微不注意,时间就溜走了,倒是没有那么忙碌,闲暇之际来博客园还是比较多的,记得上次在逛博问的时候看到有同志在问MVC中Cookie过期后如何作相关处理,他在阐述那么多页面不可能都去一个个手动处理。其实MVC很牛逼的地方就是把Attribute利用的非常完美,接下来就来看下它是如何做到的吧!

第一步、我们要定义一个登录过滤标签-LoginFilterAttribute并且继承AuthorizeAttribute。来看下它内部是啥样子

  1. // Summary:
  2. // Represents an attribute that is used to restrict access by callers to an
  3. // action method.
  4. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
  5. public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
  6. {
  7. // Summary:
  8. // Initializes a new instance of the System.Web.Mvc.AuthorizeAttribute class.
  9. public AuthorizeAttribute();
  10.  
  11. // Summary:
  12. // Gets or sets the user roles.
  13. //
  14. // Returns:
  15. // The user roles.
  16. public string Roles { get; set; }
  17. //
  18. // Summary:
  19. // Gets the unique identifier for this attribute.
  20. //
  21. // Returns:
  22. // The unique identifier for this attribute.
  23. public override object TypeId { get; }
  24. //
  25. // Summary:
  26. // Gets or sets the authorized users.
  27. //
  28. // Returns:
  29. // The authorized users.
  30. public string Users { get; set; }
  31.  
  32. // Summary:
  33. // When overridden, provides an entry point for custom authorization checks.
  34. //
  35. // Parameters:
  36. // httpContext:
  37. // The HTTP context, which encapsulates all HTTP-specific information about
  38. // an individual HTTP request.
  39. //
  40. // Returns:
  41. // true if the user is authorized; otherwise, false.
  42. //
  43. // Exceptions:
  44. // System.ArgumentNullException:
  45. // The httpContext parameter is null.
  46. protected virtual bool AuthorizeCore(HttpContextBase httpContext);
  47. //
  48. // Summary:
  49. // Processes HTTP requests that fail authorization.
  50. //
  51. // Parameters:
  52. // filterContext:
  53. // Encapsulates the information for using System.Web.Mvc.AuthorizeAttribute.
  54. // The filterContext object contains the controller, HTTP context, request context,
  55. // action result, and route data.
  56. protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
  57. //
  58. // Summary:
  59. // Called when a process requests authorization.
  60. //
  61. // Parameters:
  62. // filterContext:
  63. // The filter context, which encapsulates information for using System.Web.Mvc.AuthorizeAttribute.
  64. //
  65. // Exceptions:
  66. // System.ArgumentNullException:
  67. // The filterContext parameter is null.
  68. public virtual void OnAuthorization(AuthorizationContext filterContext);
  69. //
  70. // Summary:
  71. // Called when the caching module requests authorization.
  72. //
  73. // Parameters:
  74. // httpContext:
  75. // The HTTP context, which encapsulates all HTTP-specific information about
  76. // an individual HTTP request.
  77. //
  78. // Returns:
  79. // A reference to the validation status.
  80. //
  81. // Exceptions:
  82. // System.ArgumentNullException:
  83. // The httpContext parameter is null.
  84. protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
  85. }

这里我们要重写OnAuthorization这个方法。

接下来就看下LoginFilterAttibute这个"儿子"是怎么完成"老子"交待的任务了。直接上code

  1. public class LoginFilterAttribute:AuthorizeAttribute
  2. {
  3.  
  4. private static string formsCookieName = FormsAuthentication.FormsCookieName;
  5.  
  6. public override void OnAuthorization(AuthorizationContext filterContext)
  7. {
  8. HttpCookie formsCookie =
  9. System.Web.CookieManager.GetCookie(formsCookieName);
  10. if (formsCookie == null)
  11. {
  12. //页面Cookie过期后返回登录页面
  13. RedirectToLoginPage(filterContext);
  14. return;
  15. }
  16.  
  17. bool autenticated = HttpContext.Current.User.Identity.IsAuthenticated;
  18.  
  19. //一旦发现身份不合法就作相应的处理.
  20. if (!autenticated )
  21. {
  22. //redirect to login
  23. RedirectToLoginPage(filterContext);
  24. return;
  25. }
  26. //if success add login data to context
  27. }
  28. private static void RedirectToLoginPage(AuthorizationContext filterContext)
  29. {
  30. if (filterContext.HttpContext.Request.IsAjaxRequest())
  31. {
  32. filterContext.Result = new JsonResult()
  33. {
  34. Data = new {
  35. status = "error",
  36. message = "Unauthorized_Message"
  37. },
  38. JsonRequestBehavior= JsonRequestBehavior.AllowGet
  39. };
  40. return;
  41. }
  42. else
  43. {
  44. //返回登录页面的相关处理..........
  45. }
    }

第二步、新建一个基类Controller-BaseController并且继承Controller。

  1. [LoginFilter]//此处就是我们上面定义的LoginFilterAttribute
  2. public abstract partial class BaseController : Controller
  3. {
  4. public BaseController(){
  5.  
  6. }
  7. //........其他相关处理
  8. }

第三步、不是有很多页面吗?那我只要在对应的Controller去继承那个BaseController就实现了,在访问任何一个页面都会去作相应的过滤和处理。

  1. Public Class LoginControllerBaseController
  2. {
  3. Public ActionResult Index()
  4. {
  5. //........
  6. return View();
  7. }
  8. }

以上纯属个人观点,如有雷同纯属巧合!谢谢阅读,如果对您有帮助,请点关注并推荐!

ASP.NET MVC中利用AuthorizeAttribute实现访问身份是否合法以及Cookie过期问题的处理的更多相关文章

  1. Asp.net Mvc中利用ValidationAttribute实现xss过滤

    在网站开发中,需要注意的一个问题就是防范XSS攻击,Asp.net mvc中已经自动为我们提供了这个功能.用户提交数据时时,在生成Action参数的过程中asp.net会对用户提交的数据进行验证,一旦 ...

  2. 解决asp.net mvc中*.resx资源文件访问报错

    个人笔记 问题重现 在asp.net mvc中,使用资源文件会出现一个问题,例如: 紧接着我进入视图界面,输入下面代码: <a href="javascript:void(0);&qu ...

  3. Asp.Net MVC 中实现跨域访问

    在ASP.Net webapi中可以使用  Microsoft.AspNet.WebApi.Cors  来实现: public static class WebApiConfig { public s ...

  4. 在Asp.Net MVC 中如何用JS访问Web.Config中appSettings的值

    应用场景: 很多时候我们要在Web.Config中添加appSettings的键值对来标识一些全局的信息,比如:调用service的domain,跳转其他网站页面的url 等等: 那么此时就涉及到了一 ...

  5. 在ASP.NET MVC中利用Aspose.cells 将查询出的数据导出为excel,并在浏览器中下载。

    正题前的唠叨 本人是才出来工作不久的小白菜一颗,技术很一般,总是会有遇到一些很简单的问题却不知道怎么做,这些问题可能是之前解决过的.发现这个问题,想着提升一下自己的技术水平,将一些学的新的'好'东西记 ...

  6. 在Asp.Net MVC中利用快递100接口实现订阅物流轨迹功能

    前言 分享一篇关于在电商系统中同步物流轨迹到本地服务器的文章,当前方案使用了快递100做为数据来源接口,这个接口是收费的,不过提供的功能还是非常强大的,有专门的售后维护团队.也有免费的方案,类似于快递 ...

  7. ASP.NET MVC中使用ASP.NET AJAX异步访问WebService

    使用过ASP.NET AJAX的朋友都知道,怎么通过ASP.NET AJAX在客户端访问WebService,其实在ASP.NET MVC中使用ASP.NET AJAX异步访问WebService 也 ...

  8. 在ASP.NET MVC3 中利用Jsonp跨域访问

    在ASP.NET MVC3 中利用Jsonp跨域访问 在信息系统开发的时,根据相关业务逻辑难免会多系统之间互相登录.一般情况下我们需要在多系统之间使用多个用户名和密码.这样客户就需要在多个系统之间重复 ...

  9. 在 ASP.NET MVC 中充分利用 WebGrid (microsoft 官方示例)

    在 ASP.NET MVC 中充分利用 WebGrid https://msdn.microsoft.com/zh-cn/magazine/hh288075.aspx Stuart Leeks 下载代 ...

随机推荐

  1. java基础集合经典训练题

    第一题:要求产生10个随机的字符串,每一个字符串互相不重复,每一个字符串中组成的字符(a-zA-Z0-9)也不相同,每个字符串长度为10; 分析:*1.看到这个题目,或许你脑海中会想到很多方法,比如判 ...

  2. Online Judge(OJ)搭建(第一版)

    搭建 OJ 需要的知识(重要性排序): Java SE(Basic Knowledge, String, FileWriter, JavaCompiler, URLClassLoader, Secur ...

  3. GreenDao 数据库:使用Raw文件夹下的数据库文件以及数据库升级

    一.使用Raw文件夹下的数据库文件 在使用GreenDao框架时,数据库和数据表都是根据生成的框架代码来自动创建的,从生成的DaoMaster中的OpenHelper类可以看出: public sta ...

  4. 简析服务端通过GT导入SHP至PG的方法

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1.背景 项目中需要在浏览器端直接上传SHP后服务端进行数据的自动入PG ...

  5. Asp.Net WebApi核心对象解析(上篇)

    生活需要自己慢慢去体验和思考,对于知识也是如此.匆匆忙忙的生活,让人不知道自己一天到晚都在干些什么,似乎每天都在忙,但又好似不知道自己到底在忙些什么.不过也无所谓,只要我们知道最后想要什么就行.不管怎 ...

  6. [原]HAproxy 代理技术原理探究

    HAproxy 技术分享 简介 HAProxy是一款提供高可用性.负载均衡以及基于TCP(第四层)和HTTP(第七层)应用的代理软件 Features 1.免费 2.能够做到4层以上代理 3.高性能 ...

  7. Java 程序优化 (读书笔记)

    --From : JAVA程序性能优化 (葛一鸣,清华大学出版社,2012/10第一版) 1. java性能调优概述 1.1 性能概述 程序性能: 执行速度,内存分配,启动时间, 负载承受能力. 性能 ...

  8. ESLint的使用笔记

    原文地址:https://csspod.com/getting-started-with-eslint/?utm_source=tuicool&utm_medium=referral 在团队协 ...

  9. VS2010 release编译下进行调试,“当前不会命中任何断点,还没有为文档加载”问题解决方案

    在release模式下调试程序,经常出现"当前不会命中任何断点,还没有为文档加载"的问题,可尝试以下方法: 1. 属性 → 配置属性 → C/C++ → 常规 → 调试信息格式:选 ...

  10. Visual Studio 2015正式发布

    Windows 10 RTM正式版要7月29日发布,微软的另一个重磅软件Visual Studio 2015已经率先发布,今天如期放出了正式版本.Visual Studio 2015包括许多新功能和更 ...