话说来到上海已经快半年了,时光如白驹过隙,稍微不注意,时间就溜走了,倒是没有那么忙碌,闲暇之际来博客园还是比较多的,记得上次在逛博问的时候看到有同志在问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过期问题的处理的更多相关文章

  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. B树——算法导论(25)

    B树 1. 简介 在之前我们学习了红黑树,今天再学习一种树--B树.它与红黑树有许多类似的地方,比如都是平衡搜索树,但它们在功能和结构上却有较大的差别. 从功能上看,B树是为磁盘或其他存储设备设计的, ...

  2. Java多线程基础学习(一)

    1. 创建线程    1.1 通过构造函数:public Thread(Runnable target, String name){}  或:public Thread(Runnable target ...

  3. node.js学习(三)简单的node程序&&模块简单使用&&commonJS规范&&深入理解模块原理

    一.一个简单的node程序 1.新建一个txt文件 2.修改后缀 修改之后会弹出这个,点击"是" 3.运行test.js 源文件 使用node.js运行之后的. 如果该路径下没有该 ...

  4. 基于AOP的MVC拦截异常让代码更优美

    与asp.net 打交道很多年,如今天微软的优秀框架越来越多,其中微软在基于mvc的思想架构,也推出了自己的一套asp.net mvc 框架,如果你亲身体验过它,会情不自禁的说‘漂亮’.回过头来,‘漂 ...

  5. java单向加密算法小结(1)--Base64算法

    从这一篇起整理一下常见的加密算法以及在java中使用的demo,首先从最简单的开始. 简单了解 Base64严格来说并不是一种加密算法,而是一种编码/解码的实现方式. 我们都知道,数据在计算机网络之间 ...

  6. 记录一则Linux SSH的互信配置过程

    需求:四台Linux主机,IP地址为192.168.10.10/11/12/13,配置登录用户的互信 1.各节点ssh-keygen生成RSA密钥和公钥 ssh-keygen -q -t rsa -N ...

  7. C#中Length和Count的区别(个人观点)

    这篇文章将会很短...短到比你的JJ还短,当然开玩笑了.网上有说过Length和count的区别,都是很含糊的,我没有发现有 文章说得比较透彻的,所以,虽然这篇文章很短,我还是希望能留在首页,听听大家 ...

  8. 【WPF】日常笔记

    本文专用于记录WPF开发中的小细节,作为备忘录使用. 1. 关于绑定: Text ="{Binding AnchorageValue,Mode=TwoWay,UpdateSourceTrig ...

  9. 用django创建一个项目

    首先你得安装好python和django,然后配置好环境变量,安装python就不说了,从配置环境变量开始 1.配置环境变量 在我的电脑处点击右键,或者打开 控制面板\系统和安全\系统 -> 左 ...

  10. Angular2 Hello World 之 2.0.0-beta.14

    公司现在采用angualrjs开发一些web应用,采用的是angular1,现在angular2已经差不多了,听说最近rc6已经出来了……其实感觉好慢啊!之前也做过一些anglar2的例子,但是没有记 ...