Click here to Skip to main content
16,022,060 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In ASP.NET Core 6, I need to get the current user in service layer

What I have tried:

This is code:
C#
public class ServiceModel
{
    private readonly IHttpContextAccessor accessor;

    public ServiceModel(IHttpContextAccessor accessor)
    {
        this.accessor = accessor;
    }
}


But User is always Null:
C#
var user = accessor.HttpContext?.User


Code in Program file:
C#
builder.Services.AddIdentity<AppUser, AppRole>(options =>
{
    options.User.AllowedUserNameCharacters =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+/ ";
    options.User.RequireUniqueEmail = false;
})
.AddEntityFrameworkStores<testContext>()
.AddUserManager<UserManager<AppUser>>()
.AddClaimsPrincipalFactory<ApplicationUserClaimsPrincipalFactory>()
.AddDefaultTokenProviders();

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
    options.Cookie.Name = "MyAppCookie";
    options.LoginPath = "/Account/Login";
});

builder.Services.AddHttpContextAccessor();


This the packages installed in Service Layer:
C#
Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.EntityFrameworkCore
Microsoft.AspNetCore.Mvc.ViewFeatures
Posted
Comments
Richard Deeming 19-Sep-24 3:56am    
Is is the User that's null, or the accessor.HttpContext?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900