ASP.NET MVC中利用AuthorizeAttribute实现访问身份是否合法以及Cookie过期问题的处理
话说来到上海已经快半年了,时光如白驹过隙,稍微不注意,时间就溜走了,倒是没有那么忙碌,闲暇之际来博客园还是比较多的,记得上次在逛博问的时候看到有同志在问MVC中Cookie过期后如何作相关处理,他在阐述那么多页面不可能都去一个个手动处理。其实MVC很牛逼的地方就是把Attribute利用的非常完美,接下来就来看下它是如何做到的吧!
第一步、我们要定义一个登录过滤标签-LoginFilterAttribute并且继承AuthorizeAttribute。来看下它内部是啥样子
- // Summary:
- // Represents an attribute that is used to restrict access by callers to an
- // action method.
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
- public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
- {
- // Summary:
- // Initializes a new instance of the System.Web.Mvc.AuthorizeAttribute class.
- public AuthorizeAttribute();
- // Summary:
- // Gets or sets the user roles.
- //
- // Returns:
- // The user roles.
- public string Roles { get; set; }
- //
- // Summary:
- // Gets the unique identifier for this attribute.
- //
- // Returns:
- // The unique identifier for this attribute.
- public override object TypeId { get; }
- //
- // Summary:
- // Gets or sets the authorized users.
- //
- // Returns:
- // The authorized users.
- public string Users { get; set; }
- // Summary:
- // When overridden, provides an entry point for custom authorization checks.
- //
- // Parameters:
- // httpContext:
- // The HTTP context, which encapsulates all HTTP-specific information about
- // an individual HTTP request.
- //
- // Returns:
- // true if the user is authorized; otherwise, false.
- //
- // Exceptions:
- // System.ArgumentNullException:
- // The httpContext parameter is null.
- protected virtual bool AuthorizeCore(HttpContextBase httpContext);
- //
- // Summary:
- // Processes HTTP requests that fail authorization.
- //
- // Parameters:
- // filterContext:
- // Encapsulates the information for using System.Web.Mvc.AuthorizeAttribute.
- // The filterContext object contains the controller, HTTP context, request context,
- // action result, and route data.
- protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
- //
- // Summary:
- // Called when a process requests authorization.
- //
- // Parameters:
- // filterContext:
- // The filter context, which encapsulates information for using System.Web.Mvc.AuthorizeAttribute.
- //
- // Exceptions:
- // System.ArgumentNullException:
- // The filterContext parameter is null.
- public virtual void OnAuthorization(AuthorizationContext filterContext);
- //
- // Summary:
- // Called when the caching module requests authorization.
- //
- // Parameters:
- // httpContext:
- // The HTTP context, which encapsulates all HTTP-specific information about
- // an individual HTTP request.
- //
- // Returns:
- // A reference to the validation status.
- //
- // Exceptions:
- // System.ArgumentNullException:
- // The httpContext parameter is null.
- protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
- }
这里我们要重写OnAuthorization这个方法。
接下来就看下LoginFilterAttibute这个"儿子"是怎么完成"老子"交待的任务了。直接上code
- public class LoginFilterAttribute:AuthorizeAttribute
- {
- private static string formsCookieName = FormsAuthentication.FormsCookieName;
- public override void OnAuthorization(AuthorizationContext filterContext)
- {
- HttpCookie formsCookie =
- System.Web.CookieManager.GetCookie(formsCookieName);
- if (formsCookie == null)
- {
- //页面Cookie过期后返回登录页面
- RedirectToLoginPage(filterContext);
- return;
- }
- bool autenticated = HttpContext.Current.User.Identity.IsAuthenticated;
- //一旦发现身份不合法就作相应的处理.
- if (!autenticated )
- {
- //redirect to login
- RedirectToLoginPage(filterContext);
- return;
- }
- //if success add login data to context
- }
- private static void RedirectToLoginPage(AuthorizationContext filterContext)
- {
- if (filterContext.HttpContext.Request.IsAjaxRequest())
- {
- filterContext.Result = new JsonResult()
- {
- Data = new {
- status = "error",
- message = "Unauthorized_Message"
- },
- JsonRequestBehavior= JsonRequestBehavior.AllowGet
- };
- return;
- }
- else
- {
- //返回登录页面的相关处理..........
- }
}
第二步、新建一个基类Controller-BaseController并且继承Controller。
- [LoginFilter]//此处就是我们上面定义的LoginFilterAttribute
- public abstract partial class BaseController : Controller
- {
- public BaseController(){
- }
- //........其他相关处理
- }
第三步、不是有很多页面吗?那我只要在对应的Controller去继承那个BaseController就实现了,在访问任何一个页面都会去作相应的过滤和处理。
- Public Class LoginController:BaseController
- {
- Public ActionResult Index()
- {
- //........
- return View();
- }
- }
以上纯属个人观点,如有雷同纯属巧合!谢谢阅读,如果对您有帮助,请点关注并推荐!
ASP.NET MVC中利用AuthorizeAttribute实现访问身份是否合法以及Cookie过期问题的处理的更多相关文章
- Asp.net Mvc中利用ValidationAttribute实现xss过滤
在网站开发中,需要注意的一个问题就是防范XSS攻击,Asp.net mvc中已经自动为我们提供了这个功能.用户提交数据时时,在生成Action参数的过程中asp.net会对用户提交的数据进行验证,一旦 ...
- 解决asp.net mvc中*.resx资源文件访问报错
个人笔记 问题重现 在asp.net mvc中,使用资源文件会出现一个问题,例如: 紧接着我进入视图界面,输入下面代码: <a href="javascript:void(0);&qu ...
- Asp.Net MVC 中实现跨域访问
在ASP.Net webapi中可以使用 Microsoft.AspNet.WebApi.Cors 来实现: public static class WebApiConfig { public s ...
- 在Asp.Net MVC 中如何用JS访问Web.Config中appSettings的值
应用场景: 很多时候我们要在Web.Config中添加appSettings的键值对来标识一些全局的信息,比如:调用service的domain,跳转其他网站页面的url 等等: 那么此时就涉及到了一 ...
- 在ASP.NET MVC中利用Aspose.cells 将查询出的数据导出为excel,并在浏览器中下载。
正题前的唠叨 本人是才出来工作不久的小白菜一颗,技术很一般,总是会有遇到一些很简单的问题却不知道怎么做,这些问题可能是之前解决过的.发现这个问题,想着提升一下自己的技术水平,将一些学的新的'好'东西记 ...
- 在Asp.Net MVC中利用快递100接口实现订阅物流轨迹功能
前言 分享一篇关于在电商系统中同步物流轨迹到本地服务器的文章,当前方案使用了快递100做为数据来源接口,这个接口是收费的,不过提供的功能还是非常强大的,有专门的售后维护团队.也有免费的方案,类似于快递 ...
- ASP.NET MVC中使用ASP.NET AJAX异步访问WebService
使用过ASP.NET AJAX的朋友都知道,怎么通过ASP.NET AJAX在客户端访问WebService,其实在ASP.NET MVC中使用ASP.NET AJAX异步访问WebService 也 ...
- 在ASP.NET MVC3 中利用Jsonp跨域访问
在ASP.NET MVC3 中利用Jsonp跨域访问 在信息系统开发的时,根据相关业务逻辑难免会多系统之间互相登录.一般情况下我们需要在多系统之间使用多个用户名和密码.这样客户就需要在多个系统之间重复 ...
- 在 ASP.NET MVC 中充分利用 WebGrid (microsoft 官方示例)
在 ASP.NET MVC 中充分利用 WebGrid https://msdn.microsoft.com/zh-cn/magazine/hh288075.aspx Stuart Leeks 下载代 ...
随机推荐
- java基础集合经典训练题
第一题:要求产生10个随机的字符串,每一个字符串互相不重复,每一个字符串中组成的字符(a-zA-Z0-9)也不相同,每个字符串长度为10; 分析:*1.看到这个题目,或许你脑海中会想到很多方法,比如判 ...
- Online Judge(OJ)搭建(第一版)
搭建 OJ 需要的知识(重要性排序): Java SE(Basic Knowledge, String, FileWriter, JavaCompiler, URLClassLoader, Secur ...
- GreenDao 数据库:使用Raw文件夹下的数据库文件以及数据库升级
一.使用Raw文件夹下的数据库文件 在使用GreenDao框架时,数据库和数据表都是根据生成的框架代码来自动创建的,从生成的DaoMaster中的OpenHelper类可以看出: public sta ...
- 简析服务端通过GT导入SHP至PG的方法
文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1.背景 项目中需要在浏览器端直接上传SHP后服务端进行数据的自动入PG ...
- Asp.Net WebApi核心对象解析(上篇)
生活需要自己慢慢去体验和思考,对于知识也是如此.匆匆忙忙的生活,让人不知道自己一天到晚都在干些什么,似乎每天都在忙,但又好似不知道自己到底在忙些什么.不过也无所谓,只要我们知道最后想要什么就行.不管怎 ...
- [原]HAproxy 代理技术原理探究
HAproxy 技术分享 简介 HAProxy是一款提供高可用性.负载均衡以及基于TCP(第四层)和HTTP(第七层)应用的代理软件 Features 1.免费 2.能够做到4层以上代理 3.高性能 ...
- Java 程序优化 (读书笔记)
--From : JAVA程序性能优化 (葛一鸣,清华大学出版社,2012/10第一版) 1. java性能调优概述 1.1 性能概述 程序性能: 执行速度,内存分配,启动时间, 负载承受能力. 性能 ...
- ESLint的使用笔记
原文地址:https://csspod.com/getting-started-with-eslint/?utm_source=tuicool&utm_medium=referral 在团队协 ...
- VS2010 release编译下进行调试,“当前不会命中任何断点,还没有为文档加载”问题解决方案
在release模式下调试程序,经常出现"当前不会命中任何断点,还没有为文档加载"的问题,可尝试以下方法: 1. 属性 → 配置属性 → C/C++ → 常规 → 调试信息格式:选 ...
- Visual Studio 2015正式发布
Windows 10 RTM正式版要7月29日发布,微软的另一个重磅软件Visual Studio 2015已经率先发布,今天如期放出了正式版本.Visual Studio 2015包括许多新功能和更 ...