Why throwing a Null reference In Razor component production?

I have a test code

@page "/admin/userInfo"
@page "/admin"
@inherits OwningComponentBase<UserManager<IdentityUser>>
@inject AuthenticationStateProvider AuthenticationStateProvider

@functions
{

}

@code
{
   public UserManager<IdentityUser> _userManager => Service;
   public string userName; /* => AuthenticationStateProvider.GetAuthenticationStateAsync().Result.User.Identity.Name; */

   public IdentityUser identity;

   protected override async Task OnInitializedAsync(){
    if (_userManager != null)
    {   
        identity = await _userManager.FindByNameAsync(userName);
    userName = "abcde";
    }
    Console.WriteLine("OnInitializedAsync");
    }
}

<h4>User Information</h4>
<h2>User name: @userName</h2>
<h4>h4 tag</h4>
@* <p>@identity.UserName</p> *@

when i am trying to get identity values, userName or identity in OnInitializedAsync can’t keep up with creation. I thought when OnInitializedAsync ends @userName or @identity.UserName be reachable to html tags. How can i solve this issue? Thanks for your help

I tried to get some values that their initialization in OnInitializedAsync method but method’s execution cant reach creation of component. How can i solve this?

You could try this code below code:

@page "/admin/userInfo"
@page "/admin"
@inherits OwningComponentBase<UserManager<IdentityUser>>
@inject AuthenticationStateProvider AuthenticationStateProvider

@code
{
   public UserManager<IdentityUser> _userManager => Service;
   public string userName;
   public IdentityUser identity;

   protected override async Task OnInitializedAsync()
   {
       var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
       var user = authState.User;

       if (user.Identity.IsAuthenticated)
       {
           userName = user.Identity.Name;
           identity = await _userManager.FindByNameAsync(userName);
       }
       else
       {
           // Handle the case where the user is not authenticated if necessary
       }
   }
}

<h4>User Information</h4>
@if(identity != null)
{
   <h2>User name: @identity.UserName</h2>
}
else
{
   <p>User is not authenticated.</p>
}
<h4>h4 tag</h4>

Leave a Comment