问题
I've got the v2 version of the Razor engine from NuGet. I'd like to compile Razor views on-the-fly using its API. However, it seems to be fully non-documented.
Every single type and member has the following documentation:
This type/member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
This is very irritating, since these are all public types and public members.
I've seen some 3rd party stuff which does compile Razor views using this library, so I know that the task should be doable too.
So, is there any actual usable documentation on how to use this API anywhere?
回答1:
I left this question open for almost a year without an answer, so I decided to post what I came up with eventually.
It is pretty clear that Razor is still undocumented, see http://msdn.microsoft.com/en-us/library/system.web.razor%28v=vs.111%29.aspx and I think it is very likely to remain undocumented.
However, how to use it can be easily determined by looking at the code of how ASP.NET MVC uses it in its Razor view engine. You can then write code based on that.
It seems that Razor also ties into the ASP.NET BuildManager
infrastructure, so you can easily get an instance of a Razor view through that. Then, you are looking for calling the ExecutePageHierarchy
method.
Here is the code:
public void ProcessRequestCore(HttpContextBase context)
{
try
{
// Create Razor page instance
var instance = BuildManager.CreateInstanceFromVirtualPath(_razorFilePath, typeof(WebPage)) as WebPage;
if (instance == null)
throw new NullReferenceException("BuildManager.CreateInstanceFromVirtualPath returned null.");
// Set up things
instance.VirtualPath = _virtualPath;
// Render the Razor page
instance.ExecutePageHierarchy(new WebPageContext(context, instance, _model), context.Response.Output);
}
catch (Exception exc)
{
Logger.WriteException(exc);
context.Response.StatusCode = 500;
}
}
来源:https://stackoverflow.com/questions/12185975/where-is-the-documentation-of-system-web-razor-v2