I'm a newbine in ASP.NET Core, I see in the User property (in ClaimsPrincipal class) in my controller, it has User.IsInRole method, so how can I override it to call my service dependency and register in my application (I don't want to use extension method).
For User.IsInRole
, it is ClaimsPrincipal
which is not registered as service, so, you could not replace ClaimsPrincipal
, and you could not override IsInRole
.
For a workaround, if you would not use extension method, you could try to implement your own ClaimsPrincipal
and Controller
.
CustomClaimsPrincipal
which is inherited from ClaimsPrincipal
public class CustomClaimsPrincipal: ClaimsPrincipal
{
public CustomClaimsPrincipal(IPrincipal principal):base(principal)
{
}
public override bool IsInRole(string role)
{
return base.IsInRole(role);
}
}
ControllerBase
to change ClaimsPrincipal User
to CustomClaimsPrincipal User
public class ControllerBase: Controller
{
public new CustomClaimsPrincipal User => new CustomClaimsPrincipal(base.User);
}
Change the Controller
from inheriting ControllerBase
.
public class HomeController : ControllerBase
{
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
var result = User.IsInRole("Admin");
return View();
}
Change the logic in public override bool IsInRole(string role)
based on your requirement
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments