C
C#7mo ago
Jonathan

Error Accessing a User in Blazor

I am trying to setup my first Blazor project after being away from dotnet for a while to chase the javsacript world and I am completely stuck on something simple. I have created a new blazor app with the template and enabled Individual Accounts for auth. I am simply trying to get the current user information for the home screen and I get an error :
Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
Unhandled exception in circuit 'G1M-mKG0EKFb3eev_tf-_Mksjrr5QqWRiMMBvnuRCh4'.
System.ObjectDisposedException: Cannot access a disposed object.
Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
Unhandled exception in circuit 'G1M-mKG0EKFb3eev_tf-_Mksjrr5QqWRiMMBvnuRCh4'.
System.ObjectDisposedException: Cannot access a disposed object.
The browser console has the error:
[Error] WebSocket connection to 'ws://localhost:5240/_blazor?id=RIqaRL19VNie_L68N5CkRg' failed: The operation couldn’t be completed. Socket is not connected
[Error] WebSocket connection to 'ws://localhost:5240/_blazor?id=RIqaRL19VNie_L68N5CkRg' failed: The operation couldn’t be completed. Socket is not connected
I have tried to do everything I can find about this. I have tried changing render modes, etc. I am at a complete loss. The home page is simply this (which I based on the sample account pages)
@page "/"
@using ExampleIssues.Components.Account
@using ExampleIssues.Data
@inject IdentityUserAccessor UserAccessor

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

@if (user != null)
{
<div>User here: @user.UserName</div>
}
else
{
<div>User Not found</div>
}

@code {

private ApplicationUser user = default!;

[CascadingParameter] private HttpContext HttpContext { get; set; } = default!;
protected override async Task OnInitializedAsync()
{
user = await UserAccessor.GetRequiredUserAsync(HttpContext);
}
}
@page "/"
@using ExampleIssues.Components.Account
@using ExampleIssues.Data
@inject IdentityUserAccessor UserAccessor

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

@if (user != null)
{
<div>User here: @user.UserName</div>
}
else
{
<div>User Not found</div>
}

@code {

private ApplicationUser user = default!;

[CascadingParameter] private HttpContext HttpContext { get; set; } = default!;
protected override async Task OnInitializedAsync()
{
user = await UserAccessor.GetRequiredUserAsync(HttpContext);
}
}
I have put the entire repo here: https://github.com/jmarbutt/ExampleIssues/tree/main/ExampleIssues
GitHub
ExampleIssues/ExampleIssues at main · jmarbutt/ExampleIssues
Contribute to jmarbutt/ExampleIssues development by creating an account on GitHub.
18 Replies
friedice
friedice7mo ago
strange, I couldn't repro this. I cloned your repo and dont get any console errors. Once in a while I do get an error here because httpcontext is null, which isnt consistent
internal sealed class IdentityUserAccessor(
UserManager<ApplicationUser> userManager,
IdentityRedirectManager redirectManager)
{
public async Task<ApplicationUser> GetRequiredUserAsync(HttpContext context)
{
var user = await userManager.GetUserAsync(context.User);

if (user is null)
{
redirectManager.RedirectToWithStatus("Account/InvalidUser",
$"Error: Unable to load user with ID '{userManager.GetUserId(context.User)}'.", context);
}

return user;
}
}
internal sealed class IdentityUserAccessor(
UserManager<ApplicationUser> userManager,
IdentityRedirectManager redirectManager)
{
public async Task<ApplicationUser> GetRequiredUserAsync(HttpContext context)
{
var user = await userManager.GetUserAsync(context.User);

if (user is null)
{
redirectManager.RedirectToWithStatus("Account/InvalidUser",
$"Error: Unable to load user with ID '{userManager.GetUserId(context.User)}'.", context);
}

return user;
}
}
No description
friedice
friedice7mo ago
i am curious how httpcontext gets created here since in the program.cs I see you only injected httpcontextaccessor and dont seem to use it
friedice
friedice7mo ago
login logic seems to work fine too
No description
friedice
friedice7mo ago
I played around with app.razor because it didn't seem to make sense to me, give this a shot. removed render mode from headoutlet, injected navmanager instead of httpcontext since that can be null in a prod enviroment
@inject NavigationManager NavigationManager
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<base href="/"/>
<link rel="stylesheet" href="./bootstrap/bootstrap.min.css"/>
<link rel="stylesheet" href="app.css"/>
<link rel="stylesheet" href="ExampleIssues.styles.css"/>
<link rel="icon" type="image/png" href="favicon.png"/>
<HeadOutlet />
</head>

<body>
<Routes @rendermode=RenderModeCheck/>
<script src="_framework/blazor.web.js"></script>
</body>

</html>

@code {
private IComponentRenderMode? RenderModeCheck => NavigationManager.Uri.Contains("/Account")
? null
: InteractiveServer;
}
@inject NavigationManager NavigationManager
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<base href="/"/>
<link rel="stylesheet" href="./bootstrap/bootstrap.min.css"/>
<link rel="stylesheet" href="app.css"/>
<link rel="stylesheet" href="ExampleIssues.styles.css"/>
<link rel="icon" type="image/png" href="favicon.png"/>
<HeadOutlet />
</head>

<body>
<Routes @rendermode=RenderModeCheck/>
<script src="_framework/blazor.web.js"></script>
</body>

</html>

@code {
private IComponentRenderMode? RenderModeCheck => NavigationManager.Uri.Contains("/Account")
? null
: InteractiveServer;
}
Jonathan
JonathanOP7mo ago
I replaced my App.razor with that and it just goes in a loop of reloading If you login and go to the home page, it just loops I just created a new blank project again, and the only thing i changed was the home page to match this:
@page "/"
@using ExampleIssues.Components.Account
@using ExampleIssues.Data
@inject IdentityUserAccessor UserAccessor

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

@if (user != null)
{
<div>User here: @user.UserName</div>
}
else
{
<div>User Not found</div>
}

@code {

private ApplicationUser user = default!;

[CascadingParameter] private HttpContext HttpContext { get; set; } = default!;
protected override async Task OnInitializedAsync()
{
user = await UserAccessor.GetRequiredUserAsync(HttpContext);
}
}
@page "/"
@using ExampleIssues.Components.Account
@using ExampleIssues.Data
@inject IdentityUserAccessor UserAccessor

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

@if (user != null)
{
<div>User here: @user.UserName</div>
}
else
{
<div>User Not found</div>
}

@code {

private ApplicationUser user = default!;

[CascadingParameter] private HttpContext HttpContext { get; set; } = default!;
protected override async Task OnInitializedAsync()
{
user = await UserAccessor.GetRequiredUserAsync(HttpContext);
}
}
friedice
friedice7mo ago
how does httpcontext get created in the scope of the current application? That's what im wondering
Jonathan
JonathanOP7mo ago
right, I tried adding:
builder.Services.AddHttpContextAccessor();
builder.Services.AddHttpContextAccessor();
and no go But if you go to the page https://localhost:7126/Account/Manage it is obviously working Maybe I am completely going this the wrong way, I just need to get my current user so I can ensure it is filtered down to their data
friedice
friedice7mo ago
no idea what's different between our env. I managed to login fine and get context of the user
Jonathan
JonathanOP7mo ago
I tried it on another computer and the same thing from a completely new project and made sure the only thing I did was replace the Home.razor
friedice
friedice7mo ago
https://gbr1b886-7097.usw3.devtunnels.ms/ I created a tunnel of my env, only thing that doesnt work is the counter/weather component. Didn't really change much either User: [email protected] Pass: Test123!
Jonathan
JonathanOP7mo ago
yeah that is working
friedice
friedice7mo ago
I can push it to a repo and you can clone it, see if that works?
Jonathan
JonathanOP7mo ago
yeah lets try that
friedice
friedice7mo ago
its bizarre that your env isn't working with the same code though
friedice
friedice7mo ago
GitHub
GitHub - friedice5467/ExampleIssues
Contribute to friedice5467/ExampleIssues development by creating an account on GitHub.
Jonathan
JonathanOP7mo ago
yeah yours is working let me see if I can find the differences
friedice
friedice7mo ago
I think I modified only app.razor and home.razor Which shouldn't really have done much in the scheme of things
Jonathan
JonathanOP7mo ago
So I found that it is something wrong with safari and the cookies or storage on my machine, I cleaned everything and it is running fine
Want results from more Discord servers?
Add your server