博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MVC之ActionFilterAttribute自定义属性
阅读量:6985 次
发布时间:2019-06-27

本文共 4066 字,大约阅读时间需要 13 分钟。

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();    }}

 

///     /// 权限拦截    ///     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]    public class PermissionFilterAttribute : ActionFilterAttribute    {        ///         /// 权限拦截        ///         ///         public override void OnActionExecuting(ActionExecutingContext filterContext)        {            if (!this.CheckAnonymous(filterContext))            {                //未登录验证                if (SessionHelper.Get("UserID") == null)                {                    //跳转到登录页面                    filterContext.RequestContext.HttpContext.Response.Redirect("~/Admin/User/Login");                }            }        }        ///         /// [Anonymous标记]验证是否匿名访问        ///         ///         /// 
public bool CheckAnonymous(ActionExecutingContext filterContext) { //验证是否是匿名访问的Action object[] attrsAnonymous = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AnonymousAttribute), true); //是否是Anonymous var Anonymous = attrsAnonymous.Length == 1; return Anonymous; } }

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

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

 

 

 其它文章 :

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

你可能感兴趣的文章
(原)InsightFace及其mxnet代码
查看>>
OpenCV学习:实现简单的图像叠加
查看>>
Intent跳转到系统应用中的拨号界面、联系人界面、短信界面及其他
查看>>
Linux内核OOM机制的详细分析(转)
查看>>
java.io包的总体框架图(转)
查看>>
MVC结构
查看>>
隐藏字
查看>>
js将long日期格式转换为标准日期格式
查看>>
Rafy 领域实体框架演示(4) - 使用本地文件型数据库 SQLCE 绿色部署
查看>>
2014第11周日
查看>>
MySQL 指定数据库字符集的 3 种方法。
查看>>
rabbitmq 介绍
查看>>
Django比较相等或者不相等的模板语法ifequal / ifnotequal
查看>>
OpenCV中phase函数计算方向场
查看>>
Rafy 框架 - 幽灵插件(假删除)
查看>>
JAVA之Mybatis基础入门二 -- 新增、更新、删除
查看>>
java获取数据库的列名,类型等信息
查看>>
专治选择困难症:Mate 10 Pro和P20 Pro之间如何选?
查看>>
瑞幸咖啡将冲刺上半年上市:叫板星巴克 已任命首席财务官
查看>>
央视主持人张羽加盟今日头条母公司字节跳动 出任副总裁
查看>>