当前位置:   article > 正文

.net core 生成html,ASP.NET Core 中如何将 .cshtml 视图文件生成为 .cs 文件

engine.razor生成cs

用的是 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);

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/750059
推荐阅读
相关标签
  

闽ICP备14008679号