.Net 472&6.0 Razor编译时的小差异
阅读原文时间:2023年09月06日阅读:1

几个月前在进行着.Net 472到6.0的升级,复用原有代码,在对Razor进行迁移中,发现原运行正常的代码,却存在报错,深入研究发现是Core下对Razor编译有一些变动。

472 创建视图

新建.Net Framework下Mvc,增加一个简单视图如下。

@{
    Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
&nbsp; &nbsp; <meta charset="utf-8" />
&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0" />
&nbsp; &nbsp; <title>@ViewData["Title"] - RazorDemo472.Web</title>
&nbsp; &nbsp; @{
&nbsp; &nbsp; &nbsp; &nbsp; var headContent = "headContent";
&nbsp; &nbsp; }
</head>
<body>
&nbsp; &nbsp; <h1>@headContent</h1>
</body>
</html>

暂不论这个变量定义的位置合不合适,或许应该全局定义,但是总归在472下是正常的,可运行的。

6.0 创建视图

新建Asp.Net Core Mvc项目,同样使用如上简单视图

@{
&nbsp; &nbsp; Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
&nbsp; &nbsp; <meta charset="utf-8" />
&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0" />
&nbsp; &nbsp; <title>@ViewData["Title"] - RazorDemo6.Web</title>
&nbsp; &nbsp; @{
&nbsp; &nbsp; &nbsp; &nbsp; var headContent = "headContent";
&nbsp; &nbsp; }
</head>
<body>
&nbsp; &nbsp; <h1>@headContent</h1>
</body>
</html>

如果只是这样,不做任何设置,编译时候就会报错。

6.0 启用运行时编译

因为整体迁移视图太多,很多视图没有如上的写法(head中的变量在body中使用),并且在472下运行正常,也没有改动Razor视图上的代码。为了加快迁移后启动的速度,不至于编译太长时间,另外也想着视图内容能够实时更新不用关了再重开,我们把构建和发布时编译Razor给关闭了。

此处在Demo中使用Razor运行时编译

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews()
&nbsp; &nbsp; .AddRazorRuntimeCompilation();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.MapDefaultControllerRoute();
app.Run();

启动项目,请求页面后便是在运行时发现页面报错。

当局部页面(整个迁移过程中只发现两个页面存在如上写法)出现如上错误后,开始找根本问题所在。

6.0因关闭了构建和发布编译,使得Razor中出现代码报错无法知道,如开启构建和发布编译,则会提示代码报错,但为何同样的代码,472可用,6.0会报错?

先开启6.0下构建和发布编译,对比下472和6.0的差异在何处。

472 IL分析

将472启动后访问页面,再找到对应视图dll,如下是复现时的dll代码,Razor视图没有分块编译,整个变量时可以在head和body共享的。

6.0 IL分析

6.0项目改造一下,开启构建与发布编译,移除Razor的运行时编译,更改一下视图内容,以避免变量构建时直接报错。

@{
&nbsp; &nbsp; Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
&nbsp; &nbsp; <meta charset="utf-8" />
&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0" />
&nbsp; &nbsp; @{
&nbsp; &nbsp; &nbsp; &nbsp; var headContent = "headContent";
&nbsp; &nbsp; }
&nbsp; &nbsp; <title>@ViewData["Title"] - RazorDemo6.Web @headContent</title>
</head>
<body>
&nbsp; &nbsp; @{
&nbsp; &nbsp; &nbsp; &nbsp; var headContent1 = "headContent1";
&nbsp; &nbsp; }
&nbsp; &nbsp; <h1>@headContent1</h1>
</body>
</html>

项目构建,从生成的项目dll中找到代码,Asp.Net Core Razor视图编译时会按照tag分块,head和body分开,以至于变量不能在两个tag间共用。

472 源码分析

  1. 首先通过ViewEngine查找视图文件。

  2. 再进入到对应的RazorViewEngine(继承父类VirtualPathProviderViewEngine)中,存在CreateView方法,返回IView,其实现即RazorView(继承父类BuildManagerCompiledView)。

  3. 开始准备ViewContext和output, 调用的是RazorView中的Render方法。

  4. Rende中调用BuildManager.GetCompliedType(ViewPath),完成将cshtml编译成动态视图类。再执行ViewPageActivator.Create方法将动态生成的视图类写入到文件夹中(注意此处是不存在则生成,存在则使用现有的)。

从其内部实现中也可看到,输出的程序集以App_Web_为前缀。

如下简便描述下BuilderManager内部调用过程。

// BuilderManager.cs
GetCompiledType()
   GetVirtualPathObjectFactory()
      GetVPathBuildResultWithAssert()
        GetVPathBuildResultWithNoAssert()
          GetVPathBuildResultInternal()
            CompilationLock.GetLock()
            CompileWebFile() //Core
              buildResult = buildProvider.GetBuildResult(results); //build
                 CreateBuildResult():BuildProvider.cs
            CompilationLock.ReleaseLock()

6.0 源码分析

当使用运行时编译时,会调用扩展方法注册到服务容器中。

builder.Services.AddControllersWithViews()
    .AddRazorRuntimeCompilation();

该扩展方法AddRazorRuntimeCompilation中会完成Razor转换所需的一些服务注册。

在这其中会实例化好RazorProjectEngine(原RazorTemplateEngine更名)。当进行视图编译时,会将文件加载,再由RazorProjectEngine负责将其语法分析,转换,构建成文本,最终生成代码并生成类。

再有了TagHelper加持后,此处生成的cSharpDocument.GeneratedCode便是会按照TagHelperScope分块。

而生成这些tagHelper的地方则处于ViewComponentTagHelperTargetExtension.cs中。

控制台中使用Razor渲染

当直接使用Razor模板引擎时,并不会按照tag分块(或是说没接入tag功能),简单使用一个例子来做对比。

<!DOCTYPE html>
<html lang="en">
<head>
&nbsp; &nbsp; <meta charset="utf-8" />
&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0" />
&nbsp; &nbsp; @{
&nbsp; &nbsp; &nbsp; &nbsp; var headContent = "headContent";
&nbsp; &nbsp; }
&nbsp; &nbsp; <title>RazorDemo6.Web @headContent</title>
</head>
<body>
&nbsp; &nbsp; @{
&nbsp; &nbsp; &nbsp; &nbsp; var headContent1 = "headContent1";
&nbsp; &nbsp; }
&nbsp; &nbsp; <h1>@headContent1</h1>
</body>
</html>

实例化RazorProjectEngine,加载文件,直接输出生成的代码。

using Microsoft.AspNetCore.Razor.Language;

var project = RazorProjectFileSystem.Create(Directory.GetCurrentDirectory());
var engine = RazorProjectEngine.Create(RazorConfiguration.Default, project, null);
var file = project.GetItem("Index.cshtml");
var codeDocument = engine.Process(file);
var code = codeDocument.GetCSharpDocument().GeneratedCode;
Console.WriteLine(code);
Console.ReadLine();

没有了TagHelper后,生成的类中不会将head和body分块。而是只按照c#代码和html分开。

// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(Razor.Template), @"default", @"/Index.cshtml")]
namespace Razor
{
&nbsp; &nbsp; #line hidden
&nbsp; &nbsp; [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"755e7386ecf54079dc3cddaaeb531c72eabc1d9a", @"/Index.cshtml")]
&nbsp; &nbsp; public class Template
&nbsp; &nbsp; {
&nbsp; &nbsp; &nbsp; &nbsp; #pragma warning disable 1998
&nbsp; &nbsp; &nbsp; &nbsp; public async override global::System.Threading.Tasks.Task ExecuteAsync()
&nbsp; &nbsp; &nbsp; &nbsp; {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; WriteLiteral("<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n&nbsp; &nbsp; <meta charset=\"utf-8\" />\r\n&nbsp; &nbsp; <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\r\n");
#nullable restore
#line 6 "C:\Projects\RazorProjectEngine\RazorLanguage.Terminal\bin\Debug\net7.0\Index.cshtml"
&nbsp; &nbsp; &nbsp; &nbsp; var headContent = "headContent";
#line default
#line hidden
#nullable disable
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; WriteLiteral("&nbsp; &nbsp; <title>RazorDemo6.Web ");
#nullable restore
#line 9 "C:\Projects\RazorProjectEngine\RazorLanguage.Terminal\bin\Debug\net7.0\Index.cshtml"
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Write(headContent);
#line default
#line hidden
#nullable disable
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; WriteLiteral("</title>\r\n</head>\r\n<body>\r\n");
#nullable restore
#line 12 "C:\Projects\RazorProjectEngine\RazorLanguage.Terminal\bin\Debug\net7.0\Index.cshtml"
&nbsp; &nbsp; &nbsp; &nbsp; var headContent1 = "headContent1";
#line default
#line hidden
#nullable disable
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; WriteLiteral("&nbsp; &nbsp; <h1>");
#nullable restore
#line 15 "C:\Projects\RazorProjectEngine\RazorLanguage.Terminal\bin\Debug\net7.0\Index.cshtml"
&nbsp; &nbsp;Write(headContent1);
#line default
#line hidden
#nullable disable
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; WriteLiteral("</h1>\r\n</body>\r\n</html>");
&nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; &nbsp; #pragma warning restore 1998
&nbsp; &nbsp; }
}
#pragma warning restore 1591
  1. https://www.cnblogs.com/artech/archive/2012/09/04/razor-view-engine-01.html
  2. https://www.cnblogs.com/artech/archive/2012/09/05/razor-view-engine-02.html
  3. https://juejin.cn/post/7130956013242417166
  4. https://github.com/dotnet/aspnetcore/tree/cd9340856ed85215a911c97c44d52373f6cba2f9/src/Razor/Microsoft.AspNetCore.Razor.Language/src

2023-06-28,望技术有成后能回来看见自己的脚步

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章