zoukankan      html  css  js  c++  java
  • MVC 自定义属性验证登录

    1.新建自定义属性类

    public class BaseFilterAttribute : FilterAttribute, IAuthorizationFilter
        {
            /// <summary>
            /// 自定义扩展属性,验证用户登录
            /// </summary>
            /// <param name="filterContext">AuthorizationContext 类将封装有关控制器、HTTP 上下文、请求上下文、路由数据、操作描述符和操作结果的信息。</param>
            public void OnAuthorization(AuthorizationContext filterContext)
            {
    
                if (filterContext.HttpContext == null)
                {
                    throw new Exception("HTTP 上下文不存在!");
                }
    
                if (filterContext.HttpContext.Session == null)
                {
                    throw new Exception("服务器Session不可用!");
                }
    
                if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) return;
                if (filterContext.HttpContext.Session[ConfigHelper.SessionCookieKey] != null) return;
    
                //if(filterContext.HttpContext.Request.Cookies[ConfigHelper.SessionCookieKey]==null)
                //    filterContext.Result = new RedirectResult("~/Views/Account/Login.cshtml");
    
                if (CookiesHelper.GetCookie(ConfigHelper.SessionCookieKey) == null)
                    filterContext.Result = new RedirectResult(ConfigHelper.SessionCookieReturnUrl);
    
            }
        }

    2.在相关的Controller类添加该自定义属性

    [BaseFilter]
        public class PreListController : BaseController
        {
        }

    3.设置不用验证的相关的方法允许匿名访问

            [AllowAnonymous]
            public ActionResult Login()
            {
                return View();
            }
  • 相关阅读:
    Java.io.outputstream.PrintStream:打印流
    Codeforces 732F. Tourist Reform (Tarjan缩点)
    退役了
    POJ 3281 Dining (最大流)
    Light oj 1233
    Light oj 1125
    HDU 5521 Meeting (最短路)
    Light oj 1095
    Light oj 1044
    HDU 3549 Flow Problem (dinic模版 && isap模版)
  • 原文地址:https://www.cnblogs.com/FH-cnblogs/p/5644498.html
Copyright © 2011-2022 走看看