I’ve added support for stand-alone Razor Views in the latest v5.8.1 Release on MyGet.
New APIs include the familiar GetViewPage()
for retrieving View Pages (e.g. under ~/Views
) and GetContentPage()
for retrieving Content Pages (e.g. under wwwroot/
) then you can use RenderToHtmlAsync()
to render the HTML output in a UTF-8 ReadOnlyMemory<char>
which you can return directly (for optimal efficiency) or if needed you can convert it to a string with .ToString()
public async Task<object> Any(MyRequest request)
{
var razor = GetPlugin<RazorFormat>();
var view = razor.GetViewPage("MyView");
if (view == null)
throw HttpError.NotFound("Razor view not found: " + "MyView");
var ret = await razor.RenderToHtmlAsync(view, new MyModel { Name = "World" },
layout:"_MyLayout"); //if Layout specified in `.cshtml` page it uses that
return ret;
}
Although for maximum efficiency you can write it to a Stream with WriteHtmlAsync()
where you can write the UTF-8 bytes directly to the OutputStream instead of above where it converts it into a UTF-8 string before converting it back to UTF-8 bytes when it writes it out again, e.g:
public async Task Any(MyRequest request)
{
var razor = GetPlugin<RazorFormat>();
var view = razor.GetViewPage("MyView");
if (view == null)
throw HttpError.NotFound("Razor view not found: " + "MyView");
await razor.WriteHtmlAsync(Response.OutputStream, view,
new MyModel { Name = "World" },
layout:"_MyLayout"); //if Layout specified in `.cshtml` page it uses that
}
If needed it also supports anonymous Types, e.g:
await razor.RenderToHtmlAsync(view, new { Name = "World" });
and in your Razor view you’ll need to specify you’re using a dynamic model, e.g:
@model dynamic