mvc 控制器忽略某些方法
需求:登录信息验证,需要忽略登录注册这些接口的验证,通过给方法加忽略过滤器实现
1.需要忽略的方法加[IgnoreLoginFilter]
2.定义忽略过滤器
public class IgnoreLoginFilterAttribute :Attribute { }
3.Global.asax注册全局过滤器
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } }
4.过滤器配置注册过滤器
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new UserAuthorizationFilter()); } }
5.通过过滤器个数来判断是否需要验证登录信息(这个效果不太好,应该判断是否有忽略验证登录信息过滤器)
public class UserAuthorizationFilter : IAuthorizationFilter { private static readonly string SID = "SID"; private static readonly string UID = "UID"; public void OnAuthorization(AuthorizationContext filterContext) { var action = filterContext.ActionDescriptor.ActionName; var attributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(IgnoreLoginFilterAttribute),false); if (attributes.Length == 0) { HttpCookie cookie = filterContext.HttpContext.Request.Cookies.Get(SID); var cookieSID = filterContext.HttpContext.Request.Cookies[SID]; var cookieUID = filterContext.HttpContext.Request.Cookies[UID]; if (cookieSID != null && cookieUID != null) { var sessionEnabel = checkSession(cookieSID.Value, cookieUID.Value); if (!sessionEnabel) { filterContext.Result = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new ResultInfo(1500, "登录超时") }; } } else { filterContext.Result = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new ResultInfo(1500, "登录超时") }; } } } private static bool checkSession(string sid, string uid) { //服务名:ZJCX.ZJCD.APP.Session.Service var resourceUri = string.Format("Session/CheckSessionStatus?sessionID={0}&zjID={1}", sid, uid); var result = ZJCX.WebAPI.Connect.WebAPIConnector.Default.Get("ZJCX.ZJCD.APP.Session.Service", resourceUri).Content.ReadAsStringAsync().Result; var resultObj = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(result, new { code = 100 }); //apiResponse = webApiConnector.Get(serviceName, resourceUri, requestServiceModel2); return resultObj.code == 0; } }
6.方法加过滤器
/// <summary> /// 登录接口 /// </summary> /// <param name="mobile"></param> /// <param name="code"></param> /// <returns></returns> [HttpPost] [IgnoreLoginFilter] public ActionResult Login(string mobile, string code) { //登录业务代码... }