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;
    }
}
posted @ 2020-01-09 14:27  淋风淼淼  阅读(869)  评论(0编辑  收藏  举报