RazorRender is a test/demo ASP.NET Core project that demonstrates two approaches for rendering Razor views and templates to HTML, suitable for scenarios like generating email content.
- Razor View Rendering: Renders standard Razor
.cshtmlviews using the built-in ASP.NET Core view engine. - RazorLight Rendering: Renders Razor templates from source strings using the RazorLight library, which is useful for dynamic or file-based templates outside the MVC pipeline.
- API Endpoints: Exposes two endpoints to render a sample email template using both approaches.
- Swagger UI: Integrated for easy API testing and exploration.
- Uses the default MVC view engine to render a
.cshtmlfile (Views/Emails/Welcome.cshtml) to an HTML string. - The
ViewRenderServicehandles the rendering by creating anActionContextand usingIRazorViewEngine. - Endpoint:
GET /api/email/razor
- Uses the RazorLight library to compile and render Razor templates from source strings.
- The template source is loaded from the file system (
Views/Emails/Welcome.cshtml) and rendered with a model. - Endpoint:
GET /api/email/razor-light
Controllers/EmailController.cs: API endpoints for rendering emails.Services/: Contains services for view rendering, template loading, and RazorLight integration.Views/Emails/Welcome.cshtml: Sample Razor view/template for email.Models/EmailModel.cs: Model used for rendering the email template.
- Build and run the project.
- Open Swagger UI at
/swaggerto test the endpoints. - Use
/api/email/razorto render using the built-in Razor engine. - Use
/api/email/razor-lightto render using RazorLight.
- Email template rendering
- Comparing Razor view engine and RazorLight
- Learning about view rendering in ASP.NET Core
You can implement a custom ITemplateSourceService to retrieve Razor template sources from a database instead of the file system. This allows dynamic template management and storage. To do this:
- Create a new implementation of
ITemplateSourceServicethat queries your database for the template content by name or key. - Register your implementation in
Startup.csorProgram.csusing dependency injection. - Update your services or controllers to use the new service as needed.
This approach enables storing and editing templates in a database, supporting scenarios like user-customizable templates or admin-managed content.
This project is for demonstration and testing purposes.
Copyright (c) 2025 Serhiy Krasovskyy xhunter74@gmail.com