Blazor

Installation

To monitor Blazor applications, add Raygun.Blazor which provides C#/Razor error monitoring, and one of the following packages, depending on the type of Blazor project you have.

  • Raygun.Blazor.Server: for Blazor Server applications.
  • Raygun.Blazor.WebAssembly: for Blazor WebAssembly applications.
  • Raygun.Blazor.Maui: for MAUI Blazor Hybrid applications.

You can install the Raygun NuGet packages either using the Nuget Package manager in your IDE or using the .NET CLI as shown bellow.

  1. In your Blazor Server project folder run:
dotnet add package Raygun.Blazor
  1. Then add the Blazor Server specific package:
dotnet add package Raygun.Blazor.Server
  1. In your Blazor WebAssembly project folder run:
dotnet add package Raygun.Blazor
  1. Then add the Blazor WebAssembly specific package:
dotnet add package Raygun.Blazor.WebAssembly
  1. Add Raygun4Maui to your project.

  2. In your MAUI Blazor Hybrid project folder run:

dotnet add package Raygun.Blazor
  1. Then add the MAUI Blazor Hybrid specific package:
dotnet add package Raygun.Blazor.Maui

Add the following code to your appsettings.json.
(Note: if you're using another type of config, add it there)

"Raygun": {
  "ApiKey": "paste_your_api_key_here"
}

Your app API key is displayed when you create a new application in your Raygun account, or can be viewed in the application settings.

In this step, setup and add a RaygunBlazorClient to your application. The instructions are different depending on the type of Blazor project you have.

Blazor Server

Add a scoped RaygunBlazorClient by calling to UseRaygunBlazor() with your WebApplication builder.

var builder = WebApplication.CreateDefault(args);
// ...
builder.UseRaygunBlazor();

Blazor WebAssembly

Add a scoped RaygunBlazorClient by calling to UseRaygunBlazor() with your WebAssemblyHostBuilder builder.

var builder = WebAssemblyHostBuilder.CreateDefault(args);
// ...
builder.UseRaygunBlazor();

MAUI Blazor Hybrid

Add a scoped RaygunBlazorClient by calling to UseRaygunBlazorMaui() with your MauiApp builder.

var builder = MauiApp.CreateBuilder();

builder
  .UseMauiApp<App>()
  // ... 
  .UseRaygunBlazorMaui();

Use RaygunErrorBoundary to wrap compoments and capture unhandled exceptions automatically.

For Blazor Server applications, You have to set @rendermode="InteractiveServer" in your HeadOutlet and Routes component to enable error capturing, as explained in Handle errors in ASP.NET Core Blazor apps

For example, in your MainLayout.razor:

<article class="content px-4">
  <RaygunErrorBoundary>
    @Body
  </RaygunErrorBoundary>
</article>

Inject the RaygunBlazorClient in your code:

@inject RaygunBlazorClient raygunClient;

And call to raygunClient.InitializeAsync() at least once.

This method should be called as early as possible in the course of using the app. The best place to do it is inside the OnAfterRenderAsync method of the main layout page. However it will also be called automatically before sending any exceptions, just in case.

To send an exception to Raygun call to raygunClient.RecordExceptionAsync(...)

This method accepts the following arguments:

  • ex: The Exception to send back to Raygun.
  • userDetails: Optional. Attach user details to exception, takes priority over IRaygunUserProvider.
  • tags: Optional. User-specified tags that should be applied to the error.
  • userCustomData: Optional. Any custom data that you you like sent with the report to assist with troubleshooting.
  • cancellationToken: Optional. A CancellationToken to allow you to cancel the current request, if necessary.

Deploy Raygun into your production environment for best results, or raise a test exception. Once we detect your first error event, the Raygun app will automatically update.

Records a Breadcrumb to help you track what was going on in your application before an error occurred.

Call to raygunClient.RecordBreadcrumb(...);

This method accepts the following arguments:

  • message: The message you want to record for this Breadcrumb.
  • type: The BreadcrumbType for the message. Defaults to BreadcrumbType.Manual.
  • category: A custom value used to arbitrarily group this Breadcrumb.
  • customData: Any custom data you want to record about application state when the Breadcrumb was recorded.

Raygun for Blazor provides two ways to attach user details to error reports:

  1. Provide UserDetails in the RecordExceptionAsync method call.
  2. Implement a IRaygunUserProvider.

User details class

The following properties can be provided as user details:

  • UserId: A unique identifier for the user
  • IsAnonymous: Flag indicating if the user is anonymous or not.
  • Email: User's email address.
  • FullName: User's full name.
  • FirstName: User's first name (what you would use if you were emailing them - "Hi {{firstName}}, ...")
  • DeviceId: Device unique identifier. Useful if sending errors from a mobile device.

All properties are strings except isAnonymous, which is a boolean. As well, they are all optional.

User details in RecordExceptionAsync

The simplest way to attach user details to an error report, is to do it when calling to RecordExceptionAsync.

Pass a UserDetails object to the method call:

var userDetails = new UserDetails() { Email = "test@example.com", FullName = "Test User", UserId = "123456" };

await RaygunClient.RecordExceptionAsync(ex, userDetails);

Implementing IRaygunUserProvider

Providing an instance of IRaygunUserProvider to the Raygun Blazor client allows you to attach user details also to errors reported automatically, for example, captured unhandled exceptions or exceptions from the JavaScript layer.

Implement an IRaygunUserProvider, for example:

public class MyUserProvider : IRaygunUserProvider
{
    public Task<UserDetails?> GetCurrentUser()
    {
        return Task.FromResult(new UserDetails());
    }
}

And inject it into the Raygun Blazor client:

builder.Services.AddSingleton<IRaygunUserProvider, MyUserProvider>();

For a complete example on how to implement a IRaygunUserProvider with the AuthenticationStateProvider check the example project file src/Raygun.Samples.Blazor.WebAssembly/Program.cs.

You can enable a throttled background message processor for the Raygun provider by setting the UseBackgroundQueue to true.

{
  "Raygun": {
    "UseBackgroundQueue": true
  }
}

Background processing is disabled by default.

You can adjust the following background processor settings as well:

  • BackgroundMessageQueueMax to set the maximum queue size.
  • BackgroundMessageWorkerCount to set the maximum number of workers.
  • BackgroundMessageWorkerBreakpoint to set a threshold on when a new worker will be added.

Check the RaygunSettings class for a complete documentation of these parameters and their default values.

The RaygunClient exposes the OnBeforeSend event listener, which allows you to modify or cancel error message requests before they are sent to Raygun.

To cancel sending a request, set the Cancel property to false inside your listener:

RaygunClient.OnBeforeSend += (sender, args) =>
{
  // Example of how to cancel sending a message to Raygun
  if (args.Request.Details.Error.Message == "Cancel me")
  {
    // If the error message is "Cancel me"
    // then cancel the send
    args.Cancel = true;
  }
}

As well, you can modify the Request payload:

RaygunClient.OnBeforeSend += (sender, args) =>
{
  args.Request.Details.Error.Message = "Changed message";
};

Raygun for Blazor supports storing error reports when they can't be sent, for example, if the communication between the server and Raygun is interrupted.

You can enable offline storage support by setting the UseOfflineStore to true.

{
  "Raygun": {
    "UseOfflineStore": true
  }
}

Offline storage is disabled by default.

You can adjust the following offline store settings as well:

  • DirectoryName to set the folder to store crash reports, relative to the system local application data.
  • MaxOfflineFiles to set the maximum number of stored reports, defaults to 50.

For example:

{
  "Raygun": {
    "UseOfflineStore": true,
    "DirectoryName": "MyApp",
    "MaxOfflineFiles": 100
  }
}

With this configuration, Raygun will store a maximum of 100 Raygun offline reports under C:\Users\<USER>\AppData\Local\MyApp.

Raygun for Blazor uses an internal logger to help facilitate the integration of the package. The default log level is "Warning". To completely disable the internal logger, set the "LogLevel" setting to "None".

For example:

{
  "Raygun": {
    "LogLevel": "None"
  }
}

For all configuration values, check the RaygunLogLevel enum.


For more details on the Raygun4Maui provider and additional documentation about this provider and configuration options that can be specified, please see the documentation for the Raygun for MAUI.


These providers are open source and are available from the Raygun.Blazor repository.