I'm looking for a way to render a Blazor component into an HTML string, so that I'll be able to use it as a templating engine to create and send emails in my web application. Ideas?
Asked
Active
Viewed 7,146 times
20
-
Now there's an official solution coming with .NET 6: https://stackoverflow.com/q/68889811/1768303 – noseratio Aug 24 '21 at 09:29
-
@noseratio's link is dead now – Bennyboy1973 Apr 03 '23 at 02:12
-
1@Bennyboy1973 the link still works for me, but here it is in its full form: https://stackoverflow.com/questions/68889811/can-we-consume-a-blazor-component-as-a-web-component-within-a-regular-non-blazor – noseratio Apr 03 '23 at 10:16
-
Works for me now, too. Hrmmm. – Bennyboy1973 Apr 03 '23 at 11:58
2 Answers
14
Agua's original answer is still good.. however
A new solution now available for this question: BlazorTemplater is a library I wrote to address this capability (as I needed this for my app!).
This library will render any .razor
component to HTML for use in emails. Supports nested components, properties, dependency injection, and can be used in Razor Component libraries.

Quango
- 12,338
- 6
- 48
- 83
-
3
-
Link to official doc : https://learn.microsoft.com/en-gb/aspnet/core/blazor/components/?view=aspnetcore-7.0#blazor-custom-elements – user160357 Dec 20 '22 at 23:06
12
Yes, you can use the test library provided by Steve Sanderson and adapt it to your needs.
This article explains how to use it : Introduction to Blazor Component Testing
.
The library can be use to generate the HTML of a component.
exemple :
var host = new TestHost();
var component = host.AddComponent<YourComponent>();
var html = component.GetMarkup();
And you can inject services you need.
host.ConfigureServices(services =>
{
service.AddSingleton<MyService>();
});

agua from mars
- 16,428
- 4
- 61
- 70