Is there a clean way to get ClaimPrincipal or IIdentity from DI? So it can be used in service layers.
This was ugly, but possible with the "good old" HttpContext.Current.User :smile:
You can use the IHttpContextAccessor in your services. If you only care about the user I'd suggest wrapping that in another service IUserAccessor or something.
C#
public class UserAccessor : IUserAccessor
{
private IHttpContextAccessor _accessor;
public UserAccessor(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public ClaimsPrincipal User => _accessor. HttpContext.User;
}
Ye, I guess that's doable, thx.
Most helpful comment
You can use the
IHttpContextAccessorin your services. If you only care about the user I'd suggest wrapping that in another serviceIUserAccessoror something.C# public class UserAccessor : IUserAccessor { private IHttpContextAccessor _accessor; public UserAccessor(IHttpContextAccessor accessor) { _accessor = accessor; } public ClaimsPrincipal User => _accessor. HttpContext.User; }