3

I'm trying to add more detailed error logging to my application, that logs the current page url whenever a circuit crashes. One way of doing this is to override the OnCircuitClosedAsync method in a custom CircuitHandler, however I don't know how to correlate a circuit id string with an active user session.

I know I can keep track of users in the CircuitHandler by injecting an IHttpContextAccessor (see this answer), but a user can have multiple tabs open, or even have multiple concurrent login sessions, and I need to know exactly which circuit id is assigned to each individual page component.

Is there a way to get the current circuit id from a Blazor component, even if the same user has multiple tabs open (i.e. multiple circuits associated with their account)?

Lázár Zsolt
  • 685
  • 8
  • 29

1 Answers1

2

Implement a scoped CircuitHandler.

In the OnCircuitOpenedAsync override, store the Circuit in app state.

In the component, fetch the circuit from your app state.

Here's a basic minimal example:

CircuitHandler

using Microsoft.AspNetCore.Components.Server.Circuits;

internal class MyCircuitHandler : CircuitHandler
{
  private IMyCircuit myCircuit;

  public MyCircuitHandler(IMyCircuit myCircuit)
  {
    this.myCircuit = myCircuit;
  }
  public override Task OnCircuitOpenedAsync(Circuit circuit, CancellationToken cancellationToken)
  {
    myCircuit.CurrentCircuit = circuit;
    return base.OnCircuitOpenedAsync(circuit, cancellationToken);
  }
}

App state


internal interface IMyCircuit
{
  Circuit CurrentCircuit { get; set; }
}

internal class MyCircuit : IMyCircuit
{
  public Circuit? CurrentCircuit { get; set; }  
}

Program.cs

builder.Services.AddScoped<IMyCircuit, MyCircuit>();
builder.Services.AddScoped<CircuitHandler, MyCircuitHandler>();

Index.razor

@page "/"
@inject IMyCircuit circuit

<h1>Circuit: @circuit?.CurrentCircuit?.Id</h1>
Mister Magoo
  • 7,452
  • 1
  • 20
  • 35