I’m working on an ASP .NET Core Web API project alongside ReactJs. My goal is to retrieve the current logged-in user’s ID. Initially, everything seems to be functioning fine during local testing. Even when I publish the project to the server and test it using Swagger, it still works seamlessly. However, when attempting to connect the API with React, the user ID turns out to be null.
Here’s the method I’m using to fetch the current user’s ID:
private async Task<string> GetCurrentUserId()
{
var user = await _userManager.GetUserAsync(_httpContextAccessor.HttpContext.User);
if (user is null)
{
user = new AppUser();
}
return user.Id;
}
In my program.cs, I’ve configured services including identity setup, controller addition, email sender, password hasher, Swagger documentation, MVC, and CORS policies.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddTransient<IEmailSender, EmailSenderService>();
builder.Services.AddScoped<IPasswordHasher<AppUser>, PasswordHasherService<AppUser>>();
builder.Services.AddSwaggerGen();
builder.Services.AddMvc();
builder.Services.AddCors(p => p.AddPolicy("corspolicy", build =>
{
build
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin();
}));
var app = builder.Build();
app.UseCors("corspolicy");
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthorization();
app.UseAuthentication();
I know that I can store userId at local in React-side and send it as a parameter to backend,but i need to get userId so many places and i can’t send a request each time.