Safely Rendering Markdown in BLazor using Razor Component Library
This project is not my idea to begin with but due to need of displaying markdown as HTML DOM on my other project I found a post by JON BLANKENSHIP following his post I have created Blazor.Markdown project to fill my need and hope fully this project would be useful to other developers.
It’s important to sanitize any user-supplied HTML that you will be rendering back as raw HTML to prevent malicious users from injecting scripts into you app and making it vulnerable to cross-site scripting (XSS) attacks. For this task, I use HtmlSanitizer , an actively-maintained, highly-configurable .NET library.
- Markdig - “a fast, powerful, CommonMark compliant, extensible Markdown processor for .NET.”
- HtmlSanitizer - “a .NET library for cleaning HTML fragments and documents from constructs that can lead to XSS attacks.”
Blazor.Markdown is available as a NuGet package:
Add the following using statement to your main _Imports.razor
@using Blazor.MarkdownOpen StartUp.cs in your project and add service of HtmlSanitizer as Scoped
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
...
services.AddScoped<IHtmlSanitizer, HtmlSanitizer>(x =>
{
// Configure sanitizer rules as needed here.
// For now, just use default rules + allow class attributes
var sanitizer = new Ganss.XSS.HtmlSanitizer();
sanitizer.AllowedAttributes.Add("class");
return sanitizer;
});
}Binding a Markdown string to rendering HTML DOM:
<MarkdownView Content="@MarkdownString"/>