I am trying to use HttpContextAccessor on my custom class(BLL class) and while i succesfully initializes the ContextAccessor meantime HttpContext itself is null.
Code in program.cs
builder.Services.AddSingleton<IUserPermissionConfig, UserPermisionConfig>();
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
var setUserPermission = app.Services.GetRequiredService<IUserPermissionConfig>();
setUserPermission.SetUserPermissionsSession(UserConstants.SYSTEM_ID);
UserPermisionConfig component code
private readonly IHttpContextAccessor _httpContextAccessor;
public UserPermisionConfig( IHttpContextAccessor httpContextAccessor)
{
_permisionServiceClient = new PermissionServiceClient();
_httpContextAccessor = httpContextAccessor ?? throw new Exception("Http context accessor is null.");
}
public async Task SetUserPermissionsSession(int systemId)
{
string userName = _httpContextAccessor.HttpContext.
User.Identity.Name; //here httpcontext is alway null
UserPermissionsModel userPermissionModel = await GetUserPermission(systemId, userName);
_httpContextAccessor.HttpContext.Session.Set(UserConstants.SESSION_USER_PERMISSIOS, ByteArrayExtensions.ToByteArray(userPermissionModel));
}
Any help ?
CodePudding user response:
CodePudding user response:
Ok, it looks like you are trying to access the HTTP context directly from Program.cs
. This is not how it works.
The HTTP context is only avialable during an incoming HTTP request.
Your IUserPermissionConfig
service must be called from the ASP.net pipeline somewhere (controller, filter, middleware).