As far as I know, the User.Identity is ClaimsIdentity which is a property in the controllerbase. We couldn't directly use it in the other methods.
If you want to access the User.Identity in other service method, I suggest you could try to inject the httpaccessor service and get the ClaimsIdentity from it.
More details, you could refer to below codes:
Create myclass:
public class Myclass
{
public IHttpContextAccessor _accessor { get; set; }
public Myclass(IHttpContextAccessor accessor)
{
_accessor = accessor;
var re = accessor.HttpContext.User.Identity as ClaimsIdentity;
int i = 0;
}
public string GetName() {
var re = _accessor.HttpContext.User.Identity as ClaimsIdentity;
string name = re.Claims.First(x => x.Type == "name").Value;
return name;
}
}
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
services.AddHttpContextAccessor();
services.AddScoped(typeof(Myclass));
}
Usage:
public class HomeController : Controller
{
private readonly ILogger _logger;
public Myclass test { get; set; }
public HomeController(ILogger logger, Myclass _test)
{
_logger = logger;
test = _test;
}
public async Task IndexAsync()
{
var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
claimsIdentity.AddClaim(new Claim("name", "aaaa"));
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity)
);
return View();
}
public async Task PrivacyAsync()
{
var re= test.GetName();
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
Result:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…