Rendering raw/unescaped HTML in Blazor

  • Gérald Barré

By default, everything you write in a razor file is escaped to prevent any injection. This is very nice to be safe by default. But there are some use cases where you want to generate an HTML string in the code and render it as-is. For instance, you can convert a markdown string to HTML and render it.

Blazor provides the type MarkupString to indicate a string is already HTML encoded. You can instantiate a MarkupString using a new or an explicit cast:

var html = "<strong>meziantou.net</strong>";

var markupString1 = new MarkupString(html);
var markupString2 = (MarkupString)html;

Here's how to implement a Markdown component using Blazor and Markdig. Markdig allows converting a Markdown string to HTML. Using a MarkupString you can render the generated HTML without Blazor encoding it.

@* convertedMarkdown is a MarkupString so it won't be encoded *@
@convertedMarkdown

@code{
    // Use MarkupString type to prevent Blazor from using HtmlEncoder.Encode
    private MarkupString convertedMarkdown;

    [Parameter]
    public string Text { get; set; }

    protected override void OnParametersSet()
    {
        // Required Markdig https://www.nuget.org/packages/Markdig/
        var html = Markdig.Markdown.ToHtml(Text ?? "");
        convertedMarkdown = (MarkupString)html; // or new MarkupString(html)
    }
}
<Markdown Text="**Demo raw HTML** by [meziantou](https://www.meziantou.net)" />

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee