ActionFilterAttribute里有OnActionExecuting方法,跟Controller一样, 同是抽象实现了IActionFilter接口。

// 登录认证特性
public class AuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session["username"] == null)
filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary { { "from", Request.Url.ToString() } }); base.OnActionExecuting(filterContext);
}
}

使用方法如下:

public class HomeController : Controller
{
[Authentication]
public ActionResult Index()
{
return View();
}
}

如果你想针对整个MVC项目的所有Action都使用此过滤器,步骤如下:

a. 确保Global.asax.cs的Application_Start方法中包含如下红色行:

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}

b. 在FilterConfig.cs文件中注册相应的特性过滤器:

public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthenticationAttribute());
}
}

如此,通过过滤器的方法实现认证和授权

另有不推荐的方法实现授权功能,自定义一个控制器类,再通过继承这个控制器类:

1、继承Controller:

1.1 参考WebForm使用方式,在派生类里自己添加了验证方法,然后在每个Action方法里调用。

派生类如下:

public class AuthenticationControllor : Controller
{
public bool Validate()
{
if (Session["username"] == null)
return false;
else
return true;
} public ActionResult RedirectLogin(bool redirect = true)
{
if (redirect)
return RedirectToAction("Login", "Home", new { from = Request.Url.ToString() });
else
return RedirectToAction("Login", "Home");
}
}

使用类如下:

public class HomeController : AuthenticationControllor
{
public ActionResult Index()
{
if (!Validate())
return RedirectLogin(); return View();
}
}

1.2 改进上面的使用,通过用Controller里有一个OnActionExecuting方法,此方法是在Action之前执行的,非常方便。

派生类如下:

public class AuthenticationControllor : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session["username"] == null)
filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary { { "from", Request.Url.ToString() } }); base.OnActionExecuting(filterContext);
}
}

使用类如下:

// 不需要多写任何逻辑代码就能判断是否登录并跳转
public class HomeController : AuthenticationControllor
{
public ActionResult Index()
{
return View();
}
}
/// <summary>
/// 权限拦截
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class PermissionFilterAttribute : ActionFilterAttribute
{
/// <summary>
/// 权限拦截
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!this.CheckAnonymous(filterContext))
{
//未登录验证
if (SessionHelper.Get("UserID") == null)
{
//跳转到登录页面
filterContext.RequestContext.HttpContext.Response.Redirect("~/Admin/User/Login");
}
}
}
/// <summary>
/// [Anonymous标记]验证是否匿名访问
/// </summary>
/// <param name="filterContext"></param>
/// <returns></returns>
public bool CheckAnonymous(ActionExecutingContext filterContext)
{
//验证是否是匿名访问的Action
object[] attrsAnonymous = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AnonymousAttribute), true);
//是否是Anonymous
var Anonymous = attrsAnonymous.Length == ;
return Anonymous;
}
}

通过写一个BaseController来进行权限的验证,这样就不需要所有需要验证的Controller加标注了,当然BaseController还可以增加其他通用的处理

/// <summary>
/// Admin后台系统公共控制器(需要验证的模块)
/// </summary>
[PermissionFilter]
public class BaseController:Controller
{ }

其它文章 :

http://www.cnblogs.com/sunkaixuan/p/4908773.html

MVC之ActionFilterAttribute自定义属性的更多相关文章

  1. MVC中ActionFilterAttribute用法并实现统一授权

    MVC中ActionFilterAttribute经常用来处理权限或者统一操作时的问题. 先写一个简单的例子,如下: 比如现在有一个用户管理中心,而这个用户管理中心需要登录授权后才能进去操作或浏览信息 ...

  2. mvc通过ActionFilterAttribute做登录检查

    1.0 创建Attribute using System; using System.Collections.Generic; using System.Linq; using System.Web; ...

  3. 创建一个ASP.NET MVC OutputCache ActionFilterAttribute

    在每一个web应用程序中, 有的情况下,你想在一段时间内缓存一个具体的页面HTML输出,因为相关的数据和处理并不是总是变化.这种缓存的响应是储存在服务器的内存中.因为没有必要的额外处理,它提供了非常快 ...

  4. ASP.NET MVC 利用ActionFilterAttribute来做权限等

    ActionFilterAttribute是Action过滤类,该属于会在执行一个action之前先执行.而ActionFilterAttribute是 MVC的一个专门处理action过滤的类.基于 ...

  5. MVC 过滤器 ActionFilterAttribute

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  6. ASP.NET MVC 通过ActionFilterAttribute来实现防止重复提交

    实现思想:每个页面打开的时候会在页面的隐藏控件自动生成一个值并将这个值赋值session,当提交方法的时候会在过滤器的时候进行获取session和页面传值过来的隐藏控件的值进行比较,如果值相同的话,重 ...

  7. MVC之ActionFilterAttribute

    1.登录页面代码: @{ ViewBag.Title = "会员登录"; Layout = "~/Views/Shared/_LayoutDialog.cshtml&qu ...

  8. MVC过滤器-->ActionFilterAttribute和HandleErrorAttribute

    自定义的action过滤器  需要继承自ActionFilterAttribute 接口 OnActionExecuting:  在方法执行之前执行 OnActionExecuted:  方法的逻辑代 ...

  9. mvc 4 ActionFilterAttribute 特性,进行权限验证

    权限验证: /// <summary> /// 管理员身份验证 /// </summary> public class BasicAuthenticationAttribute ...

随机推荐

  1. 为何jsp 在resin下乱码,但在tomcat下却工作良好的问题

    关于JSP页面中的pageEncoding和contentType两种属性的区别:       pageEncoding是jsp文件本身的编码       contentType的charset是指服 ...

  2. mysql对表的操作

    创建表 简单的方式 CREATE TABLE person ( number INT(11), name VARCHAR(255), birthday DATE ); 或者是 CREATE TABLE ...

  3. [Contest20171102]简单数据结构题

    给一棵$n$个点的数,点权开始为$0$,有$q$次操作,每次操作选择一个点,把周围一圈点点权$+1$,在该操作后你需要输出当前周围一圈点点权的异或和. 由于输出量较大,设第$i$个询问输出为$ans_ ...

  4. 【枚举】【贪心】 Codeforces Round #398 (Div. 2) B. The Queue

    卡题意……妈的智障 一个人的服务时间完整包含在整个工作时间以内. 显然,如果有空档的时间,并且能再下班之前完结,那么直接输出即可,显然取最左侧的空档最优. 如果没有的话,就要考虑“挤掉”某个人,就是在 ...

  5. python3 开发面试题(创建表结构)6.9

    纯sql语句写出: '''设计 图书管理系统 表结构: - 书 - 书名 - 作者 - 姓名 - 出版社 - 出版社名称 - 地址 一本书只能由一家出版社出版 --> 多对一(书对出版社) 一本 ...

  6. 【java 正则表达式】记录所有在java中使用正则表达式的情况

    本篇记录在java中邂逅正则表达式的所有美丽瞬间.因为在java和js中正则表达式的语法并不一致. 1.匹配字符串中有出现[2.1开头或者&2.1或者&3.1等的] Pattern m ...

  7. oracle 对应的JDBC驱动 版本

    Oracle版本 jdk版本 推荐jar包 备注 Oracle 8i JDK 1.1.x classes111.zip   Oracle 8i JDK 1.1.x classes12.zip   Or ...

  8. LNMP第二部分nginx、php配置

    内容概要:一. nginx.confvim /usr/local/nginx/conf/nginx.conf //清空原来的配置,加入如下内容:user nobody nobody;worker_pr ...

  9. javascript快速入门26--XPath

    XPath 简介 XPath 是一门在 XML 文档中查找信息的语言.XPath 可用来在 XML 文档中对元素和属性进行遍历.XPath 是 W3C XSLT 标准的主要元素,并且 XQuery 和 ...

  10. FX Composer VS RenderMonkey 【转】

    http://blog.csdn.net/debugconsole/article/details/50905398 FX COMPOSER 其实编辑一个shader到debug它,有很多方法,很多方 ...