在您的解决方案中选择您的 cshtml 文件,打开属性窗格(默认为 F4)并输入“RazorGenerator”(无引号)作为自定义工具。这将在您构建项目时生成一个 C# 源文件。
编辑 - 也实际执行生成的类
这更加困难,您可能找不到像 RazorGenerator 这样的预构建自定义工具来为您完成此任务。我会看一下 RazorGenerator 源代码,看看他们是如何构建自定义工具/扩展方面的。我可能会分叉 RazorGenerator 代码并对其进行修改以满足我的需要。
这是我用来从剃刀标记生成类型的方法。这里有一些你可能会忽略的特定于 MVC 的杂乱无章(例如,添加引用程序集的额外代码,因此编译不会失败)。
private Type CompileRazorView(string virtualPath, FileInfo file, Assembly partialViewAssembly)
{
var config = WebConfigurationManager.OpenWebConfiguration("~/Views/web.config");
var section = config.GetSectionGroup("system.web.webPages.razor") as RazorWebSectionGroup;
var host = MvcWebRazorHostFactory.CreateHostFromConfig(section, virtualPath);
var engine = new RazorTemplateEngine(host);
using (var stream = file.OpenRead())
{
using (var reader = new StreamReader(stream))
{
var result = engine.GenerateCode(reader);
string code = null;
using (var tw = new StringWriter())
{
CodeProvider.GenerateCodeFromCompileUnit(result.GeneratedCode, tw, new CodeGeneratorOptions());
tw.Flush();
code = tw.ToString();
}
var compilerParameters = new CompilerParameters()
{
MainClass = host.DefaultClassName,
GenerateInMemory = true,
IncludeDebugInformation = true,
};
var thisAssembly = Application.GetType().Assembly;
var thisAssemblyName = thisAssembly.GetName();
var referencedAssemblies = new List<AssemblyName>();
referencedAssemblies.Add(thisAssemblyName);
referencedAssemblies.Add(partialViewAssembly.GetName());
referencedAssemblies.AddRange(partialViewAssembly.GetReferencedAssemblies());
foreach (var applicationReference in thisAssembly.GetReferencedAssemblies())
{
var assembly = Assembly.Load(applicationReference.FullName);
referencedAssemblies.Add(assembly.GetName());
referencedAssemblies.AddRange(assembly.GetReferencedAssemblies());
}
var binPath = Path.GetDirectoryName(thisAssemblyName.CodeBase);
var distinctReferences = referencedAssemblies.Distinct((a, b) =>
string.Equals(a.FullName, b.FullName, StringComparison.OrdinalIgnoreCase)).ToList();
foreach (var reference in distinctReferences)
{
var referencedAssembly = Assembly.Load(reference.FullName).CodeBase.Substring("file:///".Length);
compilerParameters.ReferencedAssemblies.Add(referencedAssembly);
}
var compilerResults = CodeProvider.CompileAssemblyFromDom(compilerParameters, result.GeneratedCode);
if (compilerResults.Errors.HasErrors)
{
var errorText = new StringBuilder();
foreach (var compilerError in compilerResults.Errors)
{
errorText.AppendLine(compilerError.ToString());
}
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"The following errors were detected attempting to compile the partial view {0}: \n{1}",
virtualPath, errorText));
}
var typeName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}",
host.DefaultNamespace, host.DefaultClassName);
var type = compilerResults.CompiledAssembly.GetType(typeName);
return type;
}
}
}
这个方法会给你一个类型,然后你可以使用反射来到达 Execute 方法,然后你可以调用它。诀窍是改变 WriteLiteral 的含义,使其输出到任意流,如 cs 文件。