I have a weird issue I can't explain.
I have a helper class in my Blazor Server Side app that does arb functions for my app. I added services.AddHttpContextAccessor(); in startup,
declared it in my helper class
public GlobalHelper(IHttpContextAccessor accessor,
IOptions<AzureADB2COptions> azureAdB2COptions,
IConfiguration configuration
)
{
_accessor = accessor;
AzureAdB2COptions = azureAdB2COptions.Value;
Configuration = configuration;
}
and then have a function to return the userid:
public string GetUserID()
{
var context = _accessor.HttpContext;
return context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
and then in my page, I just want to display it first on a button click event:
@inject Classes.GlobalHelper _helper
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
string currentCount = "test";
void IncrementCount()
{
var test4 = httpContextAccessor.HttpContext;
var authState = AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.Result.User;
if (user.Identity.IsAuthenticated)
{
try
{
currentCount = _helper.GetUserID().Result;
}
catch (Exception ex)
{
currentCount = ex.ToString();
}
}
else
{
Console.WriteLine("The user is NOT authenticated.");
}
}
}
If I just debug locally, this works fine. As soon as I publish this to an app service in Azure... I get a nullreferenceexception on accessing the httpcontextaccessor in the globalhelper class. This line:
return context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
What could I be doing wrong so that the httpcontext is null in the app service and not in debug on my local machine?
The HttpContext is not available, at least most of the time, in Blazor Server App. You shouldn't try to access it, and you shouldn't use IHttpContextAccessor. Read more here:
https://github.com/aspnet/AspNetCore/issues/14090
https://github.com/aspnet/AspNetCore/issues/13903
https://github.com/aspnet/AspNetCore/issues/12432#issuecomment-534315513
https://github.com/aspnet/AspNetCore/issues/5330#issuecomment-413928731
Note: You may access Authentication State in Blazor Server App via the AuthenticationStateProvider object and authorization components such as AuthorizeView, AuthorizeRouteView and CascadingAuthenticationState depending on what you want to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With