Ignore specific Sonar rule in specific file in dotnet C#

In SonarQube CE 9.9 with the latest sonar-scanner I want to ignore a sonar-rule for a single line of code in a single file.

e.g. see this code:

var client = new MailKit.Net.Smtp.SmtpClient
{
  ServerCertificateValidationCallback = (_, _, _, _) => true // accept any certificate
};

The above code violates SonarQube rule S4830
see https://sonarqube-ce.rsint.net/coding_rules?rule_key=csharpsquid%3AS4830&open=csharpsquid%3AS4830

In this case it is perfectly ok to not check the server’s certificate

In my dotnet core project (with .csproj file) I want to ignore the S4830 check for that particular line of code, but keep that check for all other lines of code. I also want to leave any other checks running for my source file.

How can I do that?

I would love to add a comment to the source code (much like sonarlint - How to ignore sonar rule to specific line of code in c#? - Stack Overflow which does not work for SonarQube checks but only for microsoft’s checks - see also Dotnet scanner seems to ignore #pragma warning disable ). This would allow me to add a comment just next to the pragma and describe why I am disabling that check here.
I tried that for the sonarqube rule and it ignored my pragma (tried #pragma warning disable S4830)

If that is not possible, I would love to ignore that line of code in the .csproj file (or second best option: that check for the whole source file).
But I am not sure how to disable that check via .csproj file and I could not find any documentation about that.
C# mentions that this can be done but doesn’t show an example.

Could anyone help me out?

Hey there.

Can you provide a sample project that reproduces the issue? We aren’t able to reproduce the issue on our side.

I have uploaded a minimal project to GitHub which tries to show my specific issue. Let me know of you need anything else

and to be more clear about the #pragma approach: this seems to work in Visual Studio when using SonarLint, but SonarScanner and the sonarQube server do ignore the #pragmas:

It seems that I found the solution:
I was ignoring the wrong SonarQube rule-ID: I was ignoring S4831, but in fact I should have ignored S4830.

What works for me:
using pragma warning disable

#pragma warning disable S4830
            client.ServerCertificateValidationCallback = (_, _, _, _) => true; // accept any certificate (for now)
#pragma warning restore S4830

What also works for me:
reducing rule severity in an .editorconfig file:

[*.cs]
dotnet_diagnostic.S4830.severity = none
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.