What's the current best solution for generatin

2019-01-30 07:41发布

问题:

I want to do this:

string template = "Hello @Model.Name! Welcome to Razor!";
string result = Razor.Parse(template, new { Name = "World" });

And it appears that http://razorengine.codeplex.com is perfect, except it's a year old.

EDIT: Turns out that RazorEngine has moved to GitHub and had a commit a few months back: https://github.com/Antaris/RazorEngine

I noticed that Service Stack has some Razor self-hosting but while there's a long page here http://razor.servicestack.net there's no "hello world you can totally do this from a console."

What's the current best solution for generating HTML from ASP.NET Razor templates within a Console Application?

回答1:

What's the current best solution for generating HTML from ASP.NET Razor templates within a Console Application?

RazorEngine. Full stop.



回答2:

ServiceStack is another option for rendering Razor view pages. Although it's optimized for integration into a ASP.NET or HttpListener Web Host (and provides API's for auto-discovering and registering view pages in a directory, re-compiling modified pages on the fly, etc), it also supports static generation of view pages:

var razor = new RazorFormat {
    VirtualPathProvider = new InMemoryVirtualPathProvider(new BasicAppHost()),
    EnableLiveReload = false, //don't scan for file system for changes
}.Init();

var page = razor.CreatePage("Hello @Model.Name! Welcome to Razor!");
var html = razor.RenderToHtml(page, new { Name = "World" });
html.Print();

Here's the stand-alone unit test of this example.

The benefits of using ServiceStack's Razor view rendering engine includes access to many of the MVC's HtmlHelpers that were ported to ServiceStack. You can also easily host a razor website from a self-hosted ServiceStack HttpListener as seen in razor-console.servicestack.net, the source code of which is available in a Self-Hosted Console Application or Windows Service.



回答3:

Nancy has a self-host option and an ability to plug Razor as a view engine.

https://github.com/NancyFx/Nancy/wiki/Hosting-nancy-with-wcf

https://github.com/NancyFx/Nancy/wiki/Razor-View-Engine



回答4:

I wouldn't call this the "current best" solution. However, I found it quite interesting and it will let you accomplish what you are trying to do. It just isn't very neatly wrapped up. http://vibrantcode.com/blog/2010/11/16/hosting-razor-outside-of-aspnet-revised-for-mvc3-rc.html/