基础提供商的间歇性问题在开放时失败

时间:2018-08-17 11:14:50

标签: c# entity-framework-6 asp.net-authorization

我创建了一个自定义授权属性,以根据用户的角色来限制用户。除了在某些间歇性情况下引发异常(“打开时提供程序失败”)之外,其他所有内容似乎都正常运行。

[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class CustomAuthorize : AuthorizeAttribute
{
    private readonly Role[] _roles;

    public CustomAuthorize(Role role)
    {
        _roles = new[] { role };
    }

    public CustomAuthorize(Role[] roles)
    {
        _roles = roles;
    }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var identity = actionContext.RequestContext
            .Principal
            .Identity;

        if (!identity.IsAuthenticated) throw new HttpResponseException(HttpStatusCode.Unauthorized);

        var resolver = GlobalConfiguration.Configuration.DependencyResolver;
        var employeeBusiness = resolver.GetService(typeof(EmployeeBusiness)) as IEmployeeBusiness;
        var user = employeeBusiness.GetAuthUserDto(identity.Name); // Exception triggers here...

        foreach (Role role in _roles)
        {
            switch (role)
            {
                case Role.Administrator: if (user.IsAdmin) return true; break;
                case Role.HRManager: if (user.IsHrManager) return true; break;
                case Role.Supervisor: if (user.IsSuperVisor) return true; break;
                case Role.Trainer: if (user.IsTrainer) return true; break;
                case Role.Trainee: if (user.IsTrainee) return true; break;
                default: break;
            }
        }

        return false;
    }
}

下面的代码是GetAuthUserDto。查明问题的困难之处在于有时会发生这种情况,而有时却没有。有人可以帮忙吗?

public AuthUserDto GetAuthUserDto(string userName)
{
    var employee = _employeeRepository.Where(c => c.UserName == userName)
        .FirstOrDefault();
    var employeeRoles = _employeeroleRepository.Where(c => c.EmployeeId == employee.Id)
        .ToList();

    AuthUserDto userDto = new AuthUserDto()
    {
        UserId = employee.Id,
        UserName = userName,
        FirstName = employee.FirstName,
        LastName = employee.LastName,
        IsHrManager = employeeroleRepository.CheckIfHr(employeeRoles),
        IsSuperVisor = employeeroleRepository.CheckIfSupervisor(employeeRoles),
        IsTrainee = employeeroleRepository.CheckIfTrainee(employeeRoles),
        IsTrainer = employeeroleRepository.CheckIfTrainer(employeeRoles),
        IsAdmin = employeeroleRepository.CheckIfAdmin(employeeRoles)
    };

    return userDto;
}

0 个答案:

没有答案