如何在ASP.NET Core中自定义/覆盖User.IsInRole

时间:2018-10-10 04:00:58

标签: asp.net asp.net-core

我是ASP.NET Core中的新手,我在控制器的User属性(在ClaimsPrincipal类中)中看到它具有User.IsInRole方法,因此如何覆盖它以调用我的服务依赖项并在其中注册我的应用程序(我不想使用扩展方法)。

2 个答案:

答案 0 :(得分:1)

对于User.IsInRole,它是ClaimsPrincipal,尚未注册为服务,因此,您不能替换ClaimsPrincipal,也不能覆盖IsInRole

要解决此问题,如果您不使用扩展方法,则可以尝试实现自己的ClaimsPrincipalController

    CustomClaimsPrincipal

    继承的
  • ClaimsPrincipal

    public class CustomClaimsPrincipal: ClaimsPrincipal
    {
    
    public CustomClaimsPrincipal(IPrincipal principal):base(principal)
    {
    
    }
    
    public override bool IsInRole(string role)
    {
        return base.IsInRole(role);
    }
    }
    
  • ControllerBaseClaimsPrincipal User更改为CustomClaimsPrincipal User

    public class ControllerBase: Controller
    {
        public new CustomClaimsPrincipal User => new CustomClaimsPrincipal(base.User);
    }
    
  • 从继承Controller更改ControllerBase

    public class HomeController : ControllerBase
    {
           public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";
        var result = User.IsInRole("Admin");
    
        return View();
    }
    
  • 根据您的要求更改public override bool IsInRole(string role)中的逻辑

答案 1 :(得分:1)

您可以使用ClaimsTransformation:

new_df = df['response'].groupby(df['country']).value_counts(normalize = True).unstack(fill_value = 0)

控制器方法:

public class Startup
{
    public void ConfigureServices(ServiceCollection services)
    {
        // ...
        services.AddTransient<IClaimsTransformation, ClaimsTramsformer>();
    }
}

public class CustomClaimsPrincipal : ClaimsPrincipal
{
    public override bool IsInRole(string role)
    {
        // ...
        return base.IsInRole(role);
    }
}

public class ClaimsTransformer : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var customPrincipal = new CustomClaimsPrincipal(principal) as ClaimsPrincipal;
        return Task.FromResult(customPrincipal);
    }
}

通过Authorize属性进行角色检查将使用您覆盖的IsInRole方法