Razor.Templating.Core 3.0.0

There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Razor.Templating.Core --version 3.0.0
                    
NuGet\Install-Package Razor.Templating.Core -Version 3.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Razor.Templating.Core" Version="3.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Razor.Templating.Core" Version="3.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Razor.Templating.Core" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Razor.Templating.Core --version 3.0.0
                    
#r "nuget: Razor.Templating.Core, 3.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Razor.Templating.Core@3.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Razor.Templating.Core&version=3.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Razor.Templating.Core&version=3.0.0
                    
Install as a Cake Tool

Razor.Templating.Core

Build+Test Downloads Coverage

Using Razor for HTML templating has never been easier. Render your .cshtml files to strings easily using this library.

This library uses precompiled Razor views provided by the Razor SDK.

Supported Application Types

.NET 6 & Above .NET 10 & Above
Preferred Version v2.1.0 3.0.0
Console
Api
Mvc
Worker Service
WPF
WinForms
Azure Functions

For older .NET versions, refer to the wiki

Supported View Features

MVC Razor View Features
ViewModel
ViewBag
ViewData
Layouts
ViewStarts
ViewImports
Partial Views
Tag Helpers
View Components
View Localization (Only MVC)
Dependency Injection into Views
@Url.ContentUrl**
@Url.RouteUrl**

**Contributors are welcome who can help to enable these unsupported features.

Applications

  • Email Templating
  • Report Generation & more

Performance

Performance of rendering the views to HTML is as fast as rendering the MVC page. The first render may be slightly slower due to the initialization. But, the subsequent renderings are significantly faster. Refer to the benchmark results here and run it for yourself in your own machine to verify the results.

Method Mean Error StdDev Gen0 Allocated
RenderViewWithModelAsync 28.73 μs 0.403 μs 0.357 μs 5.8594 24 KB

Runtime Compilation

From .NET 10, the Razor runtime compilation APIs are marked as obsolete. As a result, they will be removed from ASP.NET Core in the future. If you're looking to save a Razor view in a database or in a separate folder outside the project and render it on the fly, that scenario is not supported. Microsoft recommends using build-time compilation by including the Razor view in the project and built as part of your app.

Installing the NuGet package

This library is available as NuGet package

Using .NET CLI

dotnet add package Razor.Templating.Core

Using Package Reference .csproj

<PackageReference Include="Razor.Templating.Core" Version="3.0.0" />

Usage - Render View With Layout

To render a view with a layout, model, ViewData, or ViewBag, call RenderAsync() on the RazorTemplateEngine static class.

RenderAsync() method

using Razor.Templating.Core;

var model = new ExampleModel()
{
    PlainText = "This text is rendered from Razor Views using Razor.Templating.Core",
    HtmlContent = "<em>You can use it to generate email content, report generation and so on</em>"
};

// Both ViewBag and ViewData should be added to the same dictionary. 
var viewDataOrViewBag = new Dictionary<string, object>();
// ViewData is the same as in MVC.
viewDataOrViewBag["Value1"] = "1";

// ViewBag.Value2 can be written as shown below. There's no change in how it's accessed in a .cshtml file.
viewDataOrViewBag["Value2"] = "2";

var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewDataOrViewBag);

Before using this code, see this article for a sample implementation: https://medium.com/@soundaranbu/render-razor-view-cshtml-to-string-in-net-core-7d125f32c79

Render a View Without a Layout

If you need to render a view without a layout, use the RenderPartialAsync() method.

RenderPartialAsync() method

var html = await RazorTemplateEngine.RenderPartialAsync("/Views/ExampleView.cshtml", model, viewDataOrViewBag);

Render Views Without Throwing Exceptions

There are TryRenderAsync() and TryRenderPartialAsync() methods which do not throw an exception if the view doesn't exist. Instead, they return a tuple indicating whether the view exists and the rendered string.

TryRenderAsync() method

var (viewExists, renderedView) = await engine.TryRenderAsync("~/Views/Feature/ExampleViewWithoutViewModel.cshtml");

TryRenderPartialAsync() method

var (viewExists, renderedView) = await engine.TryRenderPartialAsync("~/Views/_ExamplePartialView.cshtml", model);

Razor Views in Library

You can organize Razor view files (.cshtml) in a separate shared Razor Class Library (RCL). See a sample library here.

The Razor Class Library's .csproj file should look like the example below. The AddRazorSupportForMvc property is required.

Also, the RCL should be referenced by the main project or by any project that invokes rendering methods such as RazorTemplateEngine.RenderAsync().

<Project Sdk="Microsoft.NET.Sdk.Razor">
  <PropertyGroup>
    <TargetFrameworks>net6.0</TargetFrameworks>
    <AddRazorSupportForMvc>true</AddRazorSupportForMvc>
  </PropertyGroup>

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>
</Project>

Dependency Injection

Dependencies can be injected directly into views using @inject in a .cshtml file. See a sample application here

In ASP.NET Core, register dependencies as shown below in Program.cs

...
builder.Services.AddTransient<ExampleService>();
// Add this after registering all other dependencies
builder.Services.AddRazorTemplating();

or in console or other applications, add as below

using Microsoft.Extensions.DependencyInjection;

// Add dependencies to the service collection
var services = new ServiceCollection();
services.AddTransient<ExampleService>();
// Add RazorTemplating after registering all dependencies
// This is important for the Razor template engine to find injected services.
services.AddRazorTemplating(); 

Once the dependencies are registered, we can use either one of these ways:

Using RazorTemplateEngine static class

var html = await RazorTemplateEngine.RenderAsync("~/Views/ExampleViewServiceInjection.cshtml");

Using IRazorTemplateEngine

  • Instead of using the RazorTemplateEngine static class, you can use the IRazorTemplateEngine interface and inject it directly into your class constructor.
public class MyService {
    private readonly IRazorTemplateEngine _razorTemplateEngine;

    public MyService (IRazorTemplateEngine razorTemplateEngine)
    {
        _razorTemplateEngine = razorTemplateEngine;
    }

    public async Task Index()
    {
        var renderedView = await _razorTemplateEngine.RenderAsync("/Views/Home/Index.cshtml");
        // do something with renderedView
    }
}

Note:

  • Please ensure that view paths are unique across all shared template projects.

Sample Applications

Please find the sample applications here

Support

If you find this helpful, consider supporting development by buying a coffee. Thanks!

alternate text is missing from this package README image

References:

Thanks to all the great articles and projects that helped bring this library to life!

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.

NuGet packages (26)

Showing the top 5 NuGet packages that depend on Razor.Templating.Core:

Package Downloads
Sitko.Core.App.Web

Sitko.Core is a set of libraries to help build .NET Core applications fast

FenixAlliance.ACL.Dependencies

Application Component for the Alliance Business Suite.

Bnsights.Core

Package Description

N3O.Umbraco.Blocks

TODO

Digizuite.Optimizely

The official integration between Digizuite DAM and Optimizely CMS.

GitHub repositories (3)

Showing the top 3 popular GitHub repositories that depend on Razor.Templating.Core:

Repository Stars
Cirx08/WeddingShare
A place for guests to view and drop pictures of the big day
LANCommander/LANCommander
sitkoru/Sitko.Core
Sitko.Core is a set of libraries to help build .NET Core applications fast
Version Downloads Last Updated
3.1.0-rc.1 0 2/18/2026
3.0.0 26,052 1/12/2026
2.1.0 1,136,839 10/14/2024
2.1.0-rc.1 1,730 9/12/2024
2.0.0 660,071 4/18/2024
2.0.0-rc.1 3,484 3/4/2024
1.9.0 989,300 8/25/2023
1.9.0-rc.2 117,227 2/25/2023
1.9.0-rc.1 230,232 11/13/2022
1.8.0 1,331,504 11/5/2022
1.8.0-rc.1 7,449 9/17/2022
1.7.1 594,833 7/2/2022
1.7.1-rc.1 14,436 2/20/2022
1.7.0 805,060 11/13/2021
1.7.0-preview.1 2,378 9/26/2021
1.6.1-rc.1 6,450 1/13/2022
1.6.0 501,540 9/26/2021
1.6.0-rc.2 8,583 5/14/2021
1.6.0-rc.1 2,094 5/13/2021
1.5.0 455,016 2/27/2021
Loading failed