.Net Core中使用AuthorizeAttribute的用户或角色授权

时间:2019-07-24 07:54:25

标签: asp.net-core .net-core

我正在使用下面的代码在ASP.Net MVC中正常工作。我需要将此代码转换为点网核心。但是这里 httpcontextbase 不能作为参数获取,并且 RedirectToRouteResult,RouteValueDictionary 会引发错误。请为.Net core提供MVC解决方案。提前谢谢。

  public class RoleAuthorizeAttribute : AuthorizeAttribute
{
    private readonly string[] permissionRoles;
    private users user = null;
    private string currentRole = null;

    public RoleAuthorizeAttribute(params string[] roles)
    {
        this.permissionRoles = roles;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        user = userHandler.GetLoginUserRecord();
        currentRole = userHandler.GetLoginUserRole();
        bool authorize = false;

        if (user != null)
            authorize =  permissionRoles.Contains(currentRole);

        return authorize;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext actionContext)
    {
        if (user == null)
        {
            actionContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "Login" }, { "controller", "Account" } });
        }
        else if (permissionRoles.Contains(currentRole) == false)
        {
            actionContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "Logout" }, { "controller", "Account" } });
        }
    }
}

0 个答案:

没有答案