1 namespace QS.Web.Extensions 2 { 3 ///4 /// 验证session、权限 状态 5 /// 6 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] 7 public class RequestFilterAttribute : ActionFilterAttribute 8 { 9 public override void OnActionExecuting(ActionExecutingContext filterContext)10 {11 FilterAttributesInfo attributes = filterContext.GetExecutingContext();12 13 switch (attributes.Action.ToUpper())14 {15 case "LOGIN":16 case "LOGINVALID":17 case "LOGOUT": break;18 default:19 //session验证20 var sessionUserInfo = filterContext.HttpContext.Session[SystemConsts.AdminSession.ToString()];21 if (null == sessionUserInfo)22 {23 var url = new UrlHelper(filterContext.RequestContext);24 var routeUrl = url.Action("Login", "Account", new { ErrorMsg = "用户信息丢失!" });25 filterContext.Result = new RedirectResult(routeUrl);26 }27 else28 {29 //参数非空验证30 foreach (var param in attributes.ParameterArray)31 {32 param.ParameterName.CheckNotNullOrEmpty(param.ParameterName);33 }34 //权限验证35 var permissions = filterContext36 .HttpContext37 .Session[SystemConsts.AdminRolePermissions.ToString()]38 as List;39 if (!permissions.Any(x =>40 x.ControllerName.ToLower() == attributes.Controller.ToLower() &&41 x.ActionName.ToLower() == attributes.Action.ToLower()))42 {43 filterContext.Result = new ContentResult() { Content = "invalid operation :no permission" };44 }45 }46 break;47 }48 base.OnActionExecuting(filterContext);49 }50 }51 }
其中涉及到获取 filterContext的方法类如下:
1 // ----------------------------------------------------------------------- 2 //3 // Copyright (c) 2016 QS.Web.Extensions. All rights reserved. 4 // 5 //谭明超 6 //2016/8/2 18:37:01 7 // ----------------------------------------------------------------------- 8 9 using System;10 using System.Collections.Generic;11 using System.Linq;12 using System.Web;13 using System.Web.Mvc;14 15 namespace QS.Web.Extensions16 {17 ///18 /// 互殴去19 /// 20 public class FilterAttributesInfo21 {22 ///23 /// 控制器名称24 /// 25 public string Controller { get; set; }26 ///27 /// 方法名称28 /// 29 public string Action { get; set; }30 ///31 /// route参数32 /// 33 public ParameterDescriptor[] ParameterArray { get; set; }34 35 }36 37 ///38 /// 获取 filter filterContext的相关属性39 /// 40 public static class FilterAttributeExtension41 {42 ///43 /// 获取当前filterContext的相关属性44 /// 45 /// 46 ///47 public static FilterAttributesInfo GetExecutingContext(this ActionExecutingContext filterContext)48 {49 return new FilterAttributesInfo50 {51 Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,52 Action = filterContext.ActionDescriptor.ActionName,53 ParameterArray = filterContext.ActionDescriptor.GetParameters()54 };55 }56 }57 58 }