zoukankan      html  css  js  c++  java
  • C# MVC 中自定义权限特性[Authorize]中对于Ajax访问的处理

    在MVC中定义自己的权限特性。

    下例中是简单的登录判断,登录信息存与Session中,如果Session中没有登录信息,那么就不通过。

    在处理无权限的时候,判断当前请求是否为Ajax请求,如果是Ajax请求,返回Json {state=-1,msg="请登录"},如过不是Ajax请求那么就直接重定向到登录页面。

    /// <summary>
    /// 授权特性
    /// </summary>
    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        string errcode = null;
    
        /// <summary>
        /// 授权核心
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var loginInfo = httpContext.Session["login"];
            if (loginInfo == null)
            {
                errcode = "NotLoggedIn";
                return false;
            }
            // 登录用户信息
            UserIdentity userIdentity = new UserIdentity((AdminInfo)loginInfo);
            httpContext.User = new UserPrincipal(userIdentity);
    
            return true;
        }
    
        /// <summary>
        /// 处理无权限请求
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            // 没有登录
            if (errcode == "NotLoggedIn")
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
                    filterContext.Result = new JsonResult
                    {
                        ContentEncoding = System.Text.Encoding.UTF8,
                        ContentType = "application/json",
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                        Data = new { state = -1, msg = "请重新登录" },
                    };
                }
                else
                {
                    filterContext.Result = new RedirectResult("/Account/Login");
                }
            }
            return;
        }
    }
  • 相关阅读:
    CodeForces 385C Bear and Prime Numbers 素数打表
    ZOJ 2853 Evolution 【简单矩阵快速幂】
    矩阵快速幂学习笔记
    USACO The Tamworth Two 模拟
    USACO Money Systems Dp 01背包
    UASCO Zero Sum DFS + Stack
    USACO Cow Pedigrees 【Dp】
    USACO Longest Prefix 【水】
    USACO Party Lamps 【Binary code solvution】【规律】
    USACO Runaround Numbers 模拟
  • 原文地址:https://www.cnblogs.com/miaolin/p/12171308.html
Copyright © 2011-2022 走看看