Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 876
StriplingWarrior Avatar asked Jun 23 '17 16:06

StriplingWarrior


People also ask

How do I add an Analysisr in .NET Core?

To install the package, right-click on the project, and select "Manage Dependencies". From the NuGet explorer, search for "Microsoft. NetFramework. Analyzers".

What are analyzers in .NET Core?

ASP.NET Core provides an MVC analyzers package intended for use with web API projects. The analyzers work with controllers annotated with ApiControllerAttribute, while building on web API conventions. The analyzers package notifies you of any controller action that: Returns an undeclared status code.


1 Answers

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://docs.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. 
like image 163
StriplingWarrior Avatar answered Sep 18 '22 22:09

StriplingWarrior