Run Razor view from API

I need to know how to render a Razor view from within a service operation.
(not very familiar with ServiceStack.Razor yet)

Lets say I define a Razor view to create some dynamic HTML content. For all intents and purposes I am just interested in the raw text that is generated from that view.
I will need that view to use a specific model to substitute data values into it.

Now, I want to get the raw dynamic content generated from that view into a DTO of a service operation on the same WebSite.

What code would I use (in a service operation) to render the Razor view (with model) to give me the raw dynamic content?

Note most of ServiceStack.Razor features are documented on the Razor Rockstars website: which includes info on how to register the RazorFormat plugin and where your Razor Views can be placed.

ServiceStack is who typically renders the Razor View which it does using the Response for your Service as the View Model into your Razor View and rendering the HTML output to the HTTP Response Stream.

But you can render a Razor View to a string using the RazorFormat by getting your view page and rendering it using your view model with:

var razor = HostContext.GetPlugin<RazorFormat>();
var razorView = razor.GetViewPage("MyView"); //e.g. /Views/MyView.cshtml
var html = razor.RenderToHtml(razorView , dto);

Thank you, I will try that.
(Was studying the rockstars code, but did not see this mechanism demonstrated anywhere.)

It is probably not a common scenario, but I found myself having to generate HTML using a DTO as input, and then returning that HTML encoded into a response of a service operation.

So It looks like I can use Razor to do that, which is what I need for now.

Yeah it’s rare but can be useful, e.g. we’re using it to generate Emails.

Hahaha! same, emails…

1 Like

I want to do the same, but within a .NET Core environment. My controller works fine for return a view using ServiceStack.Mvc, but when I trying to use the above code. It can not find GetViewPage and RenderToHtml functions.

.NET Core Razor uses a completely different implementation that’s built on top of MVC Razor, see: