Exploring the .NET 8 Blazor HtmlRenderer for email message templating

Published on

The release of .NET 8 exposed the HtmlRenderer for rendering Blazor components independently of the ASP.NET Core hosting environment with a significant driving factor being the ability to generate HTML fragments for emails or generating content for sites statically.

As someone who personally settled on RazorEngineCore as my preferred method I want to investigate what a Blazor replacement might look like and how it might perform.

Andrew Lock has an excellent series of posts covering exploration of .NET 8 features when they were in preview, you can find his post on Rendering Blazor components to a string here.

RazorEngineCore

I'll start with a little context in to how one might use RazorEngineCore to provide email templates before taking a dive into Blazor.

First we have a strongly typed base message model that different messages can extend:

EmailMessageModel.cs

namespace MailRendering.Models;

public abstract record EmailMessageModel()
{
    public abstract string? PreHeaderText { get; }
}

You'll notice the PreHeaderText. This property is always present in the email message layout and so is required for all message models. If this isn't required, a far simpler system for model binding can be used.

Then I'll create a simple Hello message model.

HelloMessageModel.cs

public record HelloMessageModel(string Name) : EmailMessageModel
{
    public override string? PreHeaderText => $"Hello, {Name}";
}

With the models created, I can add some Razor pages, our message layout and hello message.

EmailMessage.cshtml

<html lang="en">
  <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  </head>
  <body style="background-color: #f4f4f4; margin: 0 !important; padding: 0 !important;">
  @if (!string.IsNullOrWhiteSpace(Model.PreHeaderText))
  {
      <div style="display:none; font-size: 1px; line-height: 1px; max-height: 0; max-width: 0; opacity: 0; overflow: hidden;">
          @Model.PreHeaderText
      </div>
  }
  <table border="0" cellpadding="0" cellspacing="0" width="100%">
      <tr>
          <td bgcolor="#ffffff" align="center">
              <table border="0" cellpadding="0" width="100%" style="max-width: 600px;">
                  <tr>
                      <td align="center" valign="top" style="padding: 25px 10px 25px 10px;font-size: 18px;">
                          Email Header
                      </td>
                  </tr>
              </table>
          </td>
      </tr>
      <tr>
          <td bgcolor="#ffffff" align="center">
              <table border="0" cellpadding="0" width="100%" style="max-width: 600px;">
                  <tr>
                      <td align="left" valign="top" style="padding: 25px 10px 25px 10px;font-size: 18px;">
                          @RenderBody()
                      </td>
                  </tr>
              </table>
          </td>
      </tr>
      <tr>
          <td bgcolor="#f4f4f4" align="center">
              <table border="0" cellpadding="0" width="100%" style="max-width: 600px;">
                  <tr>
                      <td align="center" valign="top" style="padding: 25px 10px 25px 10px;font-size: 18px;">
                          Email Footer
                      </td>
                  </tr>
              </table>
          </td>
      </tr>
  </table>
  </body>
  </html>

Hello.cshtml

@{
  Layout = "EmailMessage";
}

<p style="margin: 0">
  Hello, @Model.Name!
</p>

And finally we can use something along the lines of the example @Include and @Layout handling that can be found on the RazerEngineCore Wiki here.

This will allow us to compile our templates like so:

var messagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Messages");
  var emailMessage = await File.ReadAllTextAsync(Path.Combine(messagePath, "EmailMessage.cshtml"));
  var helloMessage = await File.ReadAllTextAsync(Path.Combine(messagePath, "Hello.cshtml"));
  
  var parts = new Dictionary<string, string>
  {
      { "EmailMessage", emailMessage },
  };
  
  var razorEngine = new RazorEngine();
  _compiledTemplate = await razorEngine.CompileAsync(helloMessage, parts);

Rendering them can be done by simply calling RunAsync on the compiled template and passing in our model.

public Task<string> RenderEmailAsync<TModel>(
  IRazorEngineCompiledTemplate template,
  TModel model)
  where TModel : IRazorEngineTemplate
{
  return template.RunAsync(model);
}

Storage, loading, saving, and/or caching of compiled templates is left up for the reader to consider implemented using a system like this.

Switching to Blazor

We'll start by creating our Blazor components with a LayoutComponentBase for the root structure of an email message with a region to place a pre-header message to show in email clients and create a simple Hello message component with a model.

_Imports.razor

@using Microsoft.AspNetCore.Components.Sections

EmailMessage.razor

@inherits LayoutComponentBase
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>
<body style="background-color: #f4f4f4; margin: 0 !important; padding: 0 !important;">
<div style="display:none; font-size: 1px; line-height: 1px; max-height: 0; max-width: 0; opacity: 0; overflow: hidden;">
    <SectionOutlet SectionName="pre-header-text" />
</div>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
    <tr>
        <td bgcolor="#ffffff" align="center">
            <table border="0" cellpadding="0" width="100%" style="max-width: 600px;">
                <tr>
                    <td align="center" valign="top" style="padding: 25px 10px 25px 10px;font-size: 18px;">
                        Email Header
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td bgcolor="#ffffff" align="center">
            <table border="0" cellpadding="0" width="100%" style="max-width: 600px;">
                <tr>
                    <td align="left" valign="top" style="padding: 25px 10px 25px 10px;font-size: 18px;">
                        @Body
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td bgcolor="#f4f4f4" align="center">
            <table border="0" cellpadding="0" width="100%" style="max-width: 600px;">
                <tr>
                    <td align="center" valign="top" style="padding: 25px 10px 25px 10px;font-size: 18px;">
                        Email Footer
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
</body>
</html>

@code {

}

This is a fairly standard email message that you might expect. A thing to consider is that this is simply a layout view with a SectionOutlet component and the @Body tag. The intention here is use this as a base for any shape of email to reduce unnecessary duplication.

Next is the Hello message component which will reference the EmailMessage layout and provide content for the SectionContent and LayoutView.

Hello.razor

@layout EmailMessage

<SectionContent SectionName="pre-header-text">
    Hello, @Name!
</SectionContent>

<LayoutView Layout="@typeof(EmailMessage)">
    <p style="margin: 0">
        Hello, @Name!
    </p>    
</LayoutView>

@code {
    [Parameter]
    public required string Name { get; set; }
}

With the components created, we will need to extend our message models to provide a dictionary of their properties for convenience building the ParameterView.

EmailMessageModel.cs

public abstract record EmailMessageModel()
{
    public abstract string? PreHeaderText { get; }

    public abstract Dictionary<string, object?> ToDictionary();
}

HelloMessageModel.cs

public record HelloMessageModel(string Name) : EmailMessageModel
{
    public override string? PreHeaderText => $"Hello, {Name}";

    public override Dictionary<string, object?> ToDictionary()
        => new()
        {
            { nameof(Name), Name },
        };
}

With the messages and models in order, we can look to the BlazorRenderer and implement our render method.

public Task<string> RenderEmailAsync<TComponent, TModel>(TModel model)
  where TComponent : IComponent
  where TModel : EmailMessageModel
  => RenderEmailAsync<TComponent>(ParameterView.FromDictionary(model.ToDictionary()));

private Task<string> RenderEmailAsync<TComponent>(ParameterView parameters)
  where TComponent: IComponent
{
  return _htmlRenderer.Dispatcher.InvokeAsync(async () =>
  {
      var output = await _htmlRenderer.RenderComponentAsync<TComponent>(parameters);
      return output.ToHtmlString();
  });
}

Trying it out

Using the renderer on it's own to render the email message works exactly as you'd expect.

When trying to run benchmarks, it became apparent using it like this may not be as straight forward as maybe I'd like, but this is probably to be expected...

System.InvalidOperationException: There is already a subscriber to the content with the given section ID 'pre-header-text'.
at Microsoft.AspNetCore.Components.Sections.SectionRegistry.Subscribe(Object identifier, SectionOutlet subscriber)
at Microsoft.AspNetCore.Components.Sections.SectionOutlet.Microsoft.AspNetCore.Components.IComponent.SetParametersAsync(ParameterView parameters)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.SupplyCombinedParameters(ParameterView directAndCascadingParameters)

This is likely going to be down to the shared Dispatcher in the HtmlRenderer. This may mean if registering it in DI with a scoped lifetime may lead to this exception occurring if trying to send more than one message during the lifetime of the request.

I think my use of sections, also released with .NET 8, is the biggest issue here. Perhaps I could get it working without them using dynamic components, by rendering the top level message and passing the component type and model through. Although I suspect this will only serve to degrade performance.

There is also always the option of simply having a Blazor component for each message and rendering them.

Conclusion

Given the issues noted above I don't think this is something I'd be jumping on any time soon while RazorEngineCore has been consistently stable and fast.

It does however make sense that some of these issues would show when trying to use a freshly exposed API that was previously used for doing anything but this... But the API being made public is a promising step forward to being able to make the switch some day in the future.

Until then, while I have a requirement to be able to leverage a mail template base layout, I can sit this update out for now...

Summary

Over the course of this post I showed a rough implementation of my current system to email templating using RazorEngineCore before how this could be migrated to use the new .NET 8 HtmlRenderer. I found an issue around using the Blazor sections and being unable to use the same instance of the renderer due to section subscriptions.