Blazor

Installation


To monitor Blazor applications, we will add both Raygun4NET which provides server side error monitoring and Raygun4JS which is a JavaScript library that will handle client side error monitoring.


Monitoring server side errors

The best way to install Raygun4Net.AspNetCore is to use the NuGet package manager. With the NuGet Visual Studio extension installed, right-click on your project and select "Manage NuGet Packages..." Make sure "Online" is highlighted in the left-hand pane, then use the top right search box to find Mindscape.Raygun4Net.AspNetCore and install it.

Alternatively, visit https://www.nuget.org/packages/Mindscape.Raygun4Net.AspNetCore/ for instructions on installation using the package manager console.


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

"RaygunSettings": {
  "ApiKey": "YOUR_APP_API_KEY"
}

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


To configure the RaygunAspNetCoreMiddleware to handle exceptions that have been triggered and send unhandled exceptions automatically.

In Startup.cs:

  1. Add using Mindscape.Raygun4Net.AspNetCore; to your using statements.
  2. Add app.UseRaygun(); to the Configure method after any other ExceptionHandling methods e.g. app.UseDeveloperExceptionPage() or app.UseExceptionHandler("/Home/Error").
  3. Add services.AddRaygun(Configuration); to the ConfigureServices method.
using Mindscape.Raygun4Net.AspNetCore;
public class Startup
{
  public Startup(IConfiguration configuration)
  {
    Configuration = configuration;
  }

  public IConfiguration Configuration { get; }

  // This method gets called by the runtime. Use this method to add services to the container.
  // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  public void ConfigureServices(IServiceCollection services)
  {
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddRaygun(Configuration);
    services.AddSingleton<WeatherForecastService>();
  }

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
    if (env.IsDevelopment())
    {
      app.UseDeveloperExceptionPage();
    }
    else
    {
      app.UseExceptionHandler("/Error");
      // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
      app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRaygun();

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
      endpoints.MapBlazorHub();
      endpoints.MapFallbackToPage("/_Host");
    });
  }
}

The above set up will cause unhandled exceptions in your application code (excluding Razor components, see the section below) to be sent to your Raygun account where you can easily view all of your error monitoring and crash report data.


Unhandled exceptions which occur during the Blazor circuit will cause a fatal error in your application. For this reason, you'll need to manually catch exceptions that occur in code inside your Razor components.

We recommend following the Blazor fundamentals documentation on global exception handling:

Once you've set this up, in your Error.razor component, you can send the caught exception to Raygun.

Shared/Error.razor:

@using Microsoft.Extensions.Logging
@using Mindscape.Raygun4Net.AspNetCore;
@using Microsoft.Extensions.Configuration;
@inject IConfiguration Configuration
@inject ILogger<Error> Logger

<CascadingValue Value=this>
  @ChildContent
</CascadingValue>

@code {
  [Parameter]
  public RenderFragment ChildContent { get; set; }

  public void ProcessError(Exception ex)
  {
    Logger.LogError("Error:ProcessError - Type: {Type} Message: {Message}", ex.GetType(), ex.Message);
    
    // Send the exception to Raygun:
    new RaygunClient(Configuration["RaygunSettings:ApiKey"]).SendInBackground(ex);
  }
}

The above instructions will set up Raygun4Net to automatically detect and send all unhandled exceptions. Sometimes you may want to send exceptions manually - such as handled exceptions from within a try/catch block within a page code snippet.

Here's an example of manually sending exceptions from a try/catch block:

try
{
  // Do something here that might go wrong
}
catch (Exception e)
{
  new RaygunClient("YOUR_APP_API_KEY").SendInBackground(e);
}

For more details about the Raygun4Net provider and additional documentation about this provider and configuration options that can be specified, please see the documentation for the ASP.NET Core provider.


Monitoring client side errors

In Pages/_Host add this snippet to your markup immediately before the closing </head> tag:

<script type="text/javascript">
  !function(a,b,c,d,e,f,g,h){a.RaygunObject=e,a[e]=a[e]||function(){
  (a[e].o=a[e].o||[]).push(arguments)},f=b.createElement(c),g=b.getElementsByTagName(c)[0],
  f.async=1,f.src=d,g.parentNode.insertBefore(f,g),h=a.onerror,a.onerror=function(b,c,d,f,g){
  h&&h(b,c,d,f,g),g||(g=new Error(b)),a[e].q=a[e].q||[],a[e].q.push({
  e:g})}}(window,document,"script","//cdn.raygun.io/raygun4js/raygun.min.js","rg4js");
</script>

This will fetch the Raygun4JS script from our CDN asynchronously so it doesn't block the page load.


Paste this at the bottom of the section in Pages/_Host, just below the blazor.server.js line.

<script type="text/javascript">
  rg4js('apiKey', 'paste_your_api_key_here');
  rg4js('enableCrashReporting', true);
  window.rg4js = rg4js;       // This is needed to connect Raygun4JS with Blazor callbacks
</script>

note: If you are pasting the script block using the instructions provided when setting up a new application, be aware that you need to include window.rg4js = rg4js; at the bottom of the script section.


For more details about the Raygun4JS provider and additional documentation about this provider and configuration options that can be specified, please see the documentation for the JavaScript provider.


User Tracking (optional)

Setup server side user tracking by setting the following information against the active RaygunClient instance.

raygunClient.UserInfo = new RaygunIdentifierMessage("users_email_address@domain.com")
{
  IsAnonymous = false,
  FullName = "Firstname Lastname",
  FirstName = "Firstname"
};

Setup client side user tracking by adding the following information to the script block at the bottom of the page in Pages/_Host.

rg4js('setUser', {
  identifier: 'users_email_address_or_unique_id',
  isAnonymous: false,
  email: 'users_email_address@domain.com',
  firstName: 'Firstname',
  fullName: 'Firstname Lastname'
});

Alternatively, this can be provided from a server rendered code section by using a JavaScript invoke call:

var userData = new
{
  Identifier = "users_email_address_or_unique_id",
  IsAnonymous = false,
  Email = "users_email_address@domain.com",
  FirstName = "Firstname",
  FullName = "Firstname Lastname"
};

await JSRuntime.InvokeVoidAsync("rg4js", "setUser", userData);

These providers are open source and are available from the Raygun4Net repository and the Raygun4JS repository