话说来到上海已经快半年了,时光如白驹过隙,稍微不注意,时间就溜走了,倒是没有那么忙碌,闲暇之际来博客园还是比较多的,记得上次在逛博问的时候看到有同志在问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. 标准产品+定制开发:专注打造企业OA、智慧政务云平台——山东森普软件,交付率最高的技术型软件公司

    一.公司简介山东森普信息技术有限公司(以下简称森普软件)是一家专门致力于移动互联网产品.企业管理软件定制开发的技术型企业.公司总部设在全国五大软件园之一的济南齐鲁软件园.森普SimPro是由Simpl ...

  2. Linux下Nodejs安装(完整详细)

    之前安装过windows下以及Mac下的node,感觉还是很方便的,不成想今天安装linux下的坑了老半天,特此记录. 首先去官网下载代码,这里一定要注意安装分两种,一种是Source Code源码, ...

  3. CSS浮动、定位

    这几天有空,整理了关于CSS浮动和定位的一些知识点,有什么欠缺的地方,欢迎大家批评指正. 一.文档流的概念指什么?有哪种方式可以让元素脱离文档流? 文档流,指的是元素排版布局过程中,元素会自动从左往右 ...

  4. 《Django By Example》第三章 中文 翻译 (个人学习,渣翻)

    书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:第三章滚烫出炉,大家请不要吐槽文中 ...

  5. C#+HtmlAgilityPack+XPath带你采集数据(以采集天气数据为例子)

    第一次接触HtmlAgilityPack是在5年前,一些意外,让我从技术部门临时调到销售部门,负责建立一些流程和寻找潜在客户,最后在阿里巴巴找到了很多客户信息,非常全面,刚开始是手动复制到Excel, ...

  6. OVS local network 连通性分析 - 每天5分钟玩转 OpenStack(132)

    前面已经创建了两个 OVS local network,今天详细分析它们之间的连通性. launch 新的 instance "cirros-vm3",网络选择 second_lo ...

  7. [自翻]fasthttp中文文档(持续更新)

    fasthttp是由valyala编写的声称快于Go官方标准库net/http包十倍的快速HTTP实现.从各方的性能测试结果来看(评测一.评测二),fasthttp作为当下最快的http Go语言包当 ...

  8. ls: 无法访问/usr/sbin/smartctl: 没有那个文件或目录

    环境:RHEL6.5 + Oracle 11.2.0.4 RAC 在安装RAC时,检查时缺少包 cvuqdisk-1.0.9-1,oracle提供脚本修复安装. 但在执行时报错: [root@orad ...

  9. org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):

    org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): da.huying.usermanag ...

  10. ASP.NET Core Loves JavaScript

    前言 在 ASP.NET 团队的 Github 的主页上,有这样一个开源项目叫:"JavaScriptsServices",那么 什么是 JavaScriptsServices 呢 ...