Search code examples
c#code-analysisroslyn-code-analysis

Enabling Microsoft's Code Analysis on .NET Core Projects


Our team uses the Code Analysis feature with a custom ruleset to cause our build to fail if we forget to do things like null checks on method arguments.

However, now as we create a new .NET Core project, it doesn't look like Code Analysis is a feature of these new projects. There is no UI for it in the Project Properties area, and adding a custom ruleset to the project as recommended here only appears to affect StyleCop Analyzers (the SAxxxx rules).

Is there any way to enable Code Analysis (CAxxxx) rules in a .NET Core project?


Solution

  • Update 2021

    FxCopAnalyzers have been deprecated, and it is now recommended to use the more limited Microsoft.CodeAnalysis.NetAnalyzers package.

    See https://github.com/dotnet/roslyn-analyzers and https://learn.microsoft.com/en-us/visualstudio/code-quality/migrate-from-fxcop-analyzers-to-net-analyzers?view=vs-2019 for more details.

    Update

    Apparently the right way to do this is to install the Microsoft.CodeAnalysis.FxCopAnalyzers NuGet package. This works great, even on ASP.NET Core projects, and doesn't require the <RunCodeAnalysis> flag at all.

    Original Answer

    I realized that there's another tag in the csproj file which actually enables code analysis. The <PropertyGroup> tag in my .csproj file now looks like this:

      <PropertyGroup>
        <TargetFramework>netstandard1.4</TargetFramework>
        <CodeAnalysisRuleSet>..\MyCompanyCodeAnalysisRules.ruleset</CodeAnalysisRuleSet>
        <RunCodeAnalysis>true</RunCodeAnalysis>
      </PropertyGroup>
    

    And it works great, at least on normal projects. An ASP.NET Core project is producing the following errors:

    CA0055 : Could not identify platform for 'C:\Source\...\bin\Debug\netcoreapp1.1\....dll'.
    CA0052 : No targets were selected.