赞
踩
用的是 ASP.NET Core 3.0
经过折腾终于通过下面的代码将 .cshtml 生成了 .cs ,但生成的 .cs 文件无法正常使用
class Program
{
static void Main(string[] args)
{
var dir = new DirectoryInfo("../Cnblogs.Web.ErrorPages/Views/Errors/");
foreach (var file in dir.GetFiles("*.cshtml"))
{
RazorToCSharp(file.Name);
}
}
private static void RazorToCSharp(string filename)
{
var baseType = filename == "default.cshtml" ?
"Microsoft.AspNetCore.Mvc.Razor.RazorPage" :
"Microsoft.AspNetCore.Mvc.Razor.RazorPage";
var projectFileSystem = RazorProjectFileSystem.Create("../Cnblogs.Web.ErrorPages/Views/Errors/");
var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, projectFileSystem, builder =>
{
builder
.SetNamespace("Cnblogs.Web.ErrorPages")
.SetBaseType(baseType)
.ConfigureClass((doc, @class) =>
{
@class.ClassName = "Error" + Path.GetFileNameWithoutExtension(filename);
});
});
RazorProjectItem projectItem = projectFileSystem.GetItem(filename, null);
RazorCodeDocument razorDocument = projectEngine.Process(projectItem);
RazorCSharpDocument csDocument = razorDocument.GetCSharpDocument();
string csString = csDocument.GeneratedCode;
var targetFilePath = projectItem.PhysicalPath.Replace(projectItem.Extension, ".Designer.cs");
File.WriteAllText(targetFilePath, csString);
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。