Skip to content

Commit

Permalink
Add check for base classes with ApiController attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
zsolt-kolbay-sonarsource committed May 1, 2024
1 parent 18ecf32 commit cdbe89b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace SonarAnalyzer.Rules.CSharp;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
Expand Down Expand Up @@ -54,7 +51,7 @@ public sealed class CallModelStateIsValid : SonarDiagnosticAnalyzer
{
var type = (INamedTypeSymbol)symbolStart.Symbol;
if (type.DerivesFrom(KnownType.Microsoft_AspNetCore_Mvc_ControllerBase)
&& !type.HasAttribute(KnownType.Microsoft_AspNetCore_Mvc_ApiControllerAttribute)
&& !HasApiControllerAttribute(type)
&& !HasActionFilterAttribute(type))
{
symbolStart.RegisterCodeBlockStartAction<SyntaxKind>(ProcessCodeBlock);
Expand Down Expand Up @@ -90,6 +87,11 @@ private static void ProcessCodeBlock(SonarCodeBlockStartAnalysisContext<SyntaxKi
}
}

private static bool HasApiControllerAttribute(ITypeSymbol type) =>
type is not null
&& (type.HasAttribute(KnownType.Microsoft_AspNetCore_Mvc_ApiControllerAttribute)
|| HasApiControllerAttribute(type.BaseType));

private static bool HasActionFilterAttribute(ISymbol symbol) =>
symbol.GetAttributes().Any(x => x.AttributeClass.DerivesFrom(KnownType.Microsoft_AspNetCore_Mvc_Filters_ActionFilterAttribute));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,15 @@ public class ControllerWithApiAttributeAtTheClassLevel : ControllerBase
}
}

public class BaseClassHasApiControllerAttribute : ControllerWithApiAttributeAtTheClassLevel
{
[HttpDelete("/[controller]")]
public string Remove(Movie movie) // Compliant, base class is decorated with the ApiController attribute
{
return "Hello!";
}
}

[Controller]
public class ControllerThatDoesNotInheritFromControllerBase
{
Expand Down

0 comments on commit cdbe89b

Please sign in to comment.