You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建针对Razor文件的有效CodeAnalysis代码分析器?

自定义Roslyn分析器无法处理Razor文件的问题

我正在开发自定义Roslyn分析器,用于在项目中强制执行自定义代码样式规则。针对.cs文件的分析器开发进展顺利,但针对.Razor/.cshtml文件的分析器始终无法正常触发诊断。

当前实现代码

public override void Initialize(AnalysisContext context)
{
    context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
    context.EnableConcurrentExecution();
    
    context.RegisterCompilationStartAction(compilationContext
        => compilationContext.RegisterSyntaxTreeAction(AnalyzeRazorFile));
}


private void AnalyzeRazorFile(SyntaxTreeAnalysisContext context)
{
    if (!context.Tree.FilePath.EndsWith(".razor") && !context.Tree.FilePath.EndsWith(".cshtml"))
        return;

    var sourceText = context.Tree.GetText();
    var lines = sourceText.Lines;

    var zz = CreateDiagnostic(
        Location.Create(context.Tree, context.Tree.GetText().Lines[0].Span));
    context.ReportDiagnostic(zz);
}

其中CreateDiagnostic是Diagnostic.Create的简单封装,我的目标是验证诊断是否能被触发,但始终没有成功。

分析器项目.csproj配置

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <LangVersion>preview</LangVersion>
    <Nullable>enable</Nullable> 
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <PropertyGroup>
    <IsPackable>true</IsPackable>
    <IncludeBuildOutput>false</IncludeBuildOutput>
    <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
    <NoWarn>RS2008</NoWarn>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Razor.Language" Version="6.0.35" />
    <PackageReference Include="Microsoft.CodeAnalysis" Version="4.11.0" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.11.0" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" />
  </ItemGroup>

  <!-- This ensures the library will be packaged as an analyzer -->
  <ItemGroup>
    <None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
  </ItemGroup>
</Project>

疑问

我查看了.NET官方的Razor分析器实现,其结构与我的代码类似,但诊断始终无法触发。我知道Blazor中有大量Razor分析器在正常运行,因此怀疑可能是Razor预编译机制导致常规Roslyn分析器无法完全支持。想了解Razor文件的诊断是如何实现的?

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 13:34:59