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?
To install the package, right-click on the project, and select "Manage Dependencies". From the NuGet explorer, search for "Microsoft. NetFramework. Analyzers".
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With