..._net472">
当前位置:   article > 正文

.Net 472&6.0 Razor编译时的小差异

net472

前言

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

问题复现

472 创建视图

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

  1. @{
  2.     Layout = null;
  3. }
  4. <!DOCTYPE html>
  5. <html lang="en">
  6. <head>
  7.     <meta charset="utf-8" />
  8.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  9.     <title>@ViewData["Title"] - RazorDemo472.Web</title>
  10.     @{
  11.         var headContent = "headContent";
  12.     }
  13. </head>
  14. <body>
  15.     <h1>@headContent</h1>
  16. </body>
  17. </html>

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

6.0 创建视图

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

  1. @{
  2.     Layout = null;
  3. }
  4. <!DOCTYPE html>
  5. <html lang="en">
  6. <head>
  7.     <meta charset="utf-8" />
  8.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  9.     <title>@ViewData["Title"] - RazorDemo6.Web</title>
  10.     @{
  11.         var headContent = "headContent";
  12.     }
  13. </head>
  14. <body>
  15.     <h1>@headContent</h1>
  16. </body>
  17. </html>

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

6.0 启用运行时编译

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

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

  1. var builder = WebApplication.CreateBuilder(args);
  2. builder.Services.AddControllersWithViews()
  3.     .AddRazorRuntimeCompilation();
  4. var app = builder.Build();
  5. app.UseHttpsRedirection();
  6. app.UseRouting();
  7. app.MapDefaultControllerRoute();
  8. app.Run();

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

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

问题分析

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

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

472 IL分析

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

257bacfcbe83dbebcc5f70ed123b060d.png

6.0 IL分析

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

  1. @{
  2.     Layout = null;
  3. }
  4. <!DOCTYPE html>
  5. <html lang="en">
  6. <head>
  7.     <meta charset="utf-8" />
  8.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  9.     @{
  10.         var headContent = "headContent";
  11.     }
  12.     <title>@ViewData["Title"] - RazorDemo6.Web @headContent</title>
  13. </head>
  14. <body>
  15.     @{
  16.         var headContent1 = "headContent1";
  17.     }
  18.     <h1>@headContent1</h1>
  19. </body>
  20. </html>

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

源码分析

472 源码分析

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

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

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

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

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

3044eb7d340c15ca6af36c57bde7b005.png

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

  1. // BuilderManager.cs
  2. GetCompiledType()
  3. GetVirtualPathObjectFactory()
  4. GetVPathBuildResultWithAssert()
  5. GetVPathBuildResultWithNoAssert()
  6. GetVPathBuildResultInternal()
  7. CompilationLock.GetLock()
  8. CompileWebFile() //Core
  9. buildResult = buildProvider.GetBuildResult(results); //build
  10. CreateBuildResult():BuildProvider.cs
  11. CompilationLock.ReleaseLock()

6.0 源码分析

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

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

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

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

42025c8eaf69556cfc319fe6a77217fe.png

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

7fb3bc0677259c9f53195b776e7b1c38.png

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

9721ec256525f38a207e5f360fa03747.png

控制台中使用Razor渲染

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

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="utf-8" />
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6.     @{
  7.         var headContent = "headContent";
  8.     }
  9.     <title>RazorDemo6.Web @headContent</title>
  10. </head>
  11. <body>
  12.     @{
  13.         var headContent1 = "headContent1";
  14.     }
  15.     <h1>@headContent1</h1>
  16. </body>
  17. </html>

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

  1. using Microsoft.AspNetCore.Razor.Language;
  2. var project = RazorProjectFileSystem.Create(Directory.GetCurrentDirectory());
  3. var engine = RazorProjectEngine.Create(RazorConfiguration.Default, project, null);
  4. var file = project.GetItem("Index.cshtml");
  5. var codeDocument = engine.Process(file);
  6. var code = codeDocument.GetCSharpDocument().GeneratedCode;
  7. Console.WriteLine(code);
  8. Console.ReadLine();

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

  1. // <auto-generated/>
  2. #pragma warning disable 1591
  3. [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(Razor.Template), @"default", @"/Index.cshtml")]
  4. namespace Razor
  5. {
  6.     #line hidden
  7.     [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"755e7386ecf54079dc3cddaaeb531c72eabc1d9a", @"/Index.cshtml")]
  8.     public class Template
  9.     {
  10.         #pragma warning disable 1998
  11.         public async override global::System.Threading.Tasks.Task ExecuteAsync()
  12.         {
  13.             WriteLiteral("<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n    <meta charset=\"utf-8\" />\r\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\r\n");
  14. #nullable restore
  15. #line 6 "C:\Projects\RazorProjectEngine\RazorLanguage.Terminal\bin\Debug\net7.0\Index.cshtml"
  16.         var headContent = "headContent";
  17. #line default
  18. #line hidden
  19. #nullable disable
  20.             WriteLiteral("    <title>RazorDemo6.Web ");
  21. #nullable restore
  22. #line 9 "C:\Projects\RazorProjectEngine\RazorLanguage.Terminal\bin\Debug\net7.0\Index.cshtml"
  23.                      Write(headContent);
  24. #line default
  25. #line hidden
  26. #nullable disable
  27.             WriteLiteral("</title>\r\n</head>\r\n<body>\r\n");
  28. #nullable restore
  29. #line 12 "C:\Projects\RazorProjectEngine\RazorLanguage.Terminal\bin\Debug\net7.0\Index.cshtml"
  30.         var headContent1 = "headContent1";
  31. #line default
  32. #line hidden
  33. #nullable disable
  34.             WriteLiteral("    <h1>");
  35. #nullable restore
  36. #line 15 "C:\Projects\RazorProjectEngine\RazorLanguage.Terminal\bin\Debug\net7.0\Index.cshtml"
  37.    Write(headContent1);
  38. #line default
  39. #line hidden
  40. #nullable disable
  41.             WriteLiteral("</h1>\r\n</body>\r\n</html>");
  42.         }
  43.         #pragma warning restore 1998
  44.     }
  45. }
  46. #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

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号