其他分享
首页 > 其他分享> > .NET MVC5专题(特性篇【用户认证】Authorize)

.NET MVC5专题(特性篇【用户认证】Authorize)

作者:互联网

/// <summary>
/// ajax跟exception一致
/// 检验登陆和权限的filter
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
public class AuthorityFilterAttribute : AuthorizeAttribute
{
    /// <summary>
    /// 未登录时返还的地址
    /// </summary>
    private string _LoginPath = "";
    public AuthorityFilterAttribute()
    {
        this._LoginPath = "/Home/Login";
    }

    public AuthorityFilterAttribute(string loginPath)
    {
        this._LoginPath = loginPath;
    }
    /// <summary>
    /// 检查用户登录
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
        || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
        {
            return;//表示支持控制器、action的AllowAnonymousAttribute
        }
        var sessionUser = HttpContext.Current.Session["CurrentUser"];//使用session
        //var memberValidation = HttpContext.Current.Request.Cookies.Get("CurrentUser");//使用cookie
        //也可以使用数据库、nosql等介质
        if (sessionUser == null || !(sessionUser is CurrentUser))
        {
            HttpContext.Current.Session["CurrentUrl"] = filterContext.RequestContext.HttpContext.Request.RawUrl;
            filterContext.Result = new RedirectResult(this._LoginPath);
        }
    }

}
福建小徐 发布了152 篇原创文章 · 获赞 122 · 访问量 6956 私信 关注

标签:Authorize,MVC5,filterContext,sessionUser,public,LoginPath,._,NET,HttpContext
来源: https://blog.csdn.net/weixin_41181778/article/details/103956200