Render Razor View(.cshtml) to String in .NET Core

Supports .NET Core 3.1, .NET 5, .NET 6 — Console, ASP.NET Core Web/Api, Worker Service, WPF/WinForms(.NET Core) Applications

In most projects, there might be one or many of the following requirements.

Generating the HTML string inside the code will be messy. Many popular frameworks have a template engine to do so. Similarly ASP.NET Core has Razor. But rendering the string out of a Razor view(.cshtml) is not straightforward in both ASP.NET Core Web Application or Console Application.

There are a few popular libraries to do so. But I’m not convinced with them because either they are slow or missing view features such as view engines, views, view components, and HTML helpers or require several lines of code or lack support for both web application & console application, or doesn’t support .NET Core 3.0+

Razor.Templating.Core to the rescue. I had to create this library out of extreme need.

Let’s get started…

In this tutorial, I’m going to render the HTML string for the Invoice from .cshtml. The source code can be found here.

Creating Razor Class Library:

Let’s create the razor class library project which will house the .cshtml files.

Create New ‘Razor Class Library’ Project
Invoice.cs

Rendering View to String in Console Application:

Installing Razor.Templating.Core using Nuget package manager
Program.cs
Output

Dependency Injection: [Since v1.4.0]

If you need to inject dependencies into your views, we can leverage the inbuilt DI system in .NET Core. Find the example project here

For ASP.NET Core Applications, in Startup.cs class, register dependencies as below:

Now anywhere from your application, render the view as usual using the static class:

Render .cshtml string using the RazorTemplateEngine static class

or inject the object using IRazorTemplateEngine interface in the constructor or parameter (from v1.8.0):

Injecting RazorTemplateEngine object using IRazorTemplateEngine interface

Inject.cshtml looks like below:

For Console Applications, use DI as below:

Look for a reference here.

GitHub Repository: https://github.com/soundaranbu/RazorTemplating

NuGet Package: https://www.nuget.org/packages/Razor.Templating.Core

Support:

If you find this helpful, consider supporting the development of this library with one or more coffee ;) Thanks!

--

--

Software Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store