Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create rule S6934: A Route attribute should be added to the controller when a route template is specified at the action level #3676

Merged
merged 15 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions rules/S6934/S6934.AspNetCore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;

public class NoActionHasHttpAttributeWithRouteController : Controller
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
{
public IActionResult Index() => View(); // Compliant

[HttpGet]
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
public IActionResult Index2() => View(); // Compliant, default behavior if not route template is defined
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved

public IActionResult Error() => View(); // Compliant
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
}

public class ctionHasHttpAttributeWithRouteController : Controller
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
{
[HttpGet("GetObject")] // Noncompliant
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
public IActionResult Get() => View();

[HttpPost("CreateObject")] // Noncompliant
public IActionResult Post() => View();

[HttpPut("UpdateObject")] // Noncompliant
public IActionResult Put() => View();

[HttpDelete("DeleteObject")] // Noncompliant
public IActionResult Delete() => View();

[HttpPatch("PatchObject")] // Noncompliant
public IActionResult Patch() => View();

[HttpHead("Head")] // Noncompliant
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
public IActionResult HttpHead() => View();

[HttpOptions("Options")] // Noncompliant
public IActionResult HttpOptions() => View();
}
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved

public class WithUserDefinedAttribute : Controller
{
[MyHttpMethod("Test")] // Compliant, behavior is user defined
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
public IActionResult Index() => View();

private sealed class MyHttpMethodAttribute(string template) : HttpMethodAttribute([template]) { }
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
}
mary-georgiou-sonarsource marked this conversation as resolved.
Show resolved Hide resolved
3 changes: 3 additions & 0 deletions rules/S6934/csharp/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{

}
125 changes: 125 additions & 0 deletions rules/S6934/csharp/rule.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
When a route template is defined through an attribute on an action method, conventional routing for that action is disabled. To maintain good practice, it's recommended not to combine conventional and attribute-based routing within a single controller. As such, the controller should exclude itself from conventional routing by applying a `[Route]` attribute.
martin-strecker-sonarsource marked this conversation as resolved.
Show resolved Hide resolved

== Why is this an issue?

In https://learn.microsoft.com/en-us/aspnet/core/mvc/overview[ASP.NET Core MVC], the https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing[routing] middleware utilizes a series of rules and conventions to identify the appropriate controller and action method to handle a specific HTTP request. This process, known as _conventional routing_, is generally established using the https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.controllerendpointroutebuilderextensions.mapcontrollerroute[`MapControllerRoute`] method. This method is typically configured in one central location for all controllers during the application setup.

antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
Conversely, _attribute routing_ allows routes to be defined at the controller or action method level. It is possible to https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing#mixed-routing-attribute-routing-vs-conventional-routing[mix both mechanisms]. Although it's permissible to employ diverse routing strategies across multiple controllers, combining both mechanisms within one controller can result in confusion and increased complexity, as illustrated below.

[source,csharp]
----
// Conventional mapping definition
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

public class PersonController
{
// Conventional routing:
// Matches e.g. /Person/Index/123
public IActionResult Index(int? id) => View();

// Attribute routing:
// Matches e.g. /Age/Ascending (and model binds "Age" to sortBy and "Ascending" to direction)
// but does not match /Person/List/Age/Ascending
[HttpGet(template: "{sortBy}/{direction}")]
public IActionResult List(string sortBy, SortOrder direction) => View();
}
----

antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
== How to fix it
mary-georgiou-sonarsource marked this conversation as resolved.
Show resolved Hide resolved

When any of the controller actions are annotated with a https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.routing.httpmethodattribute[`HttpMethodAttribute`] with a route template, you should specify a route template on the controller with the https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.routeattribute[`RouteAttribute`].
martin-strecker-sonarsource marked this conversation as resolved.
Show resolved Hide resolved

=== Code examples

==== Noncompliant code example

[source,csharp,diff-id=1,diff-type=noncompliant]
----
public class PersonController: Controller
{
// Matches /Person/Index/123
public IActionResult Index(int? id) => View();

// Matches /Age/Ascending
[HttpGet(template: "{sortBy}/{direction}")] // Noncompliant: The "Index" and the "List" actions are
// reachable via different routing mechanisms and routes
public IActionResult List(string sortBy, SortOrder direction) => View();
}
----
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved

==== Compliant solution

[source,csharp,diff-id=1,diff-type=compliant]
----
[Route("[controller]/{action=Index}")]
public class PersonController: Controller
{
// Matches /Person/Index/123
[Route("{id?}")]
public IActionResult Index(int? id) => View();

// Matches Person/List/Age/Ascending
[HttpGet("{sortBy}/{direction}")] // Compliant: The route is relative to the controller
public IActionResult List(string sortBy, SortOrder direction) => View();
}
----

antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
There are also alternative options to prevent the mixing of conventional and attribute-based routing:

[source,csharp]
----
// Option 1. Replace the attribute-based routing with a conventional route
app.MapControllerRoute(
name: "Lists",
pattern: "{controller}/List/{sortBy}/{direction}",
defaults: new { action = "List" } ); // Matches Person/List/Age/Ascending

// Option 2. Use a binding, that does not depend on route templates
public class PersonController: Controller
{
// Matches Person/List?sortBy=Age&direction=Ascending
[HttpGet] // Compliant: Parameters are bound from the query string
public IActionResult List(string sortBy, SortOrder direction) => View();
}

// Option 3. Use an absolute route
public class PersonController: Controller
{
// Matches Person/List/Age/Ascending
[HttpGet("/[controller]/[action]/{sortBy}/{direction}")] // Illustrate the expected route by starting with "/"
public IActionResult List(string sortBy, SortOrder direction) => View();
}
----

== Resources

=== Documentation

* Microsoft Learn - https://learn.microsoft.com/en-us/aspnet/core/mvc/overview[Overview of ASP.NET Core MVC]
* Microsoft Learn - https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing[Routing to controller actions in ASP.NET Core]
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.routing.httpmethodattribute[HttpMethodAttribute Class]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.routeattribute[RouteAttribute Class]
mary-georgiou-sonarsource marked this conversation as resolved.
Show resolved Hide resolved

=== Articles & blog posts

* Medium - https://medium.com/quick-code/routing-in-asp-net-core-c433bff3f1a4[Routing in ASP.NET Core]
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Specify the RouteAttribute when an HttpMethodAttribute is specified at an action level

=== Highlighting

* Primary location: Controller class declaration identifier
* Secondary location: The argument for the "template" parameter of the HttpMethodAttribute applied to the controller action method declaration


endif::env-github,rspecator-view[]
25 changes: 25 additions & 0 deletions rules/S6934/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
"title": "Avoid using both attribute and conventional routing simultaneously within the same controller",
"type": "CODE_SMELL",
mary-georgiou-sonarsource marked this conversation as resolved.
Show resolved Hide resolved
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"asp.net"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-6934",
"sqKey": "S6934",
"scope": "Main",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "partial",
mary-georgiou-sonarsource marked this conversation as resolved.
Show resolved Hide resolved
"code": {
"impacts": {
"MAINTAINABILITY": "HIGH"
},
"attribute": "CLEAR"
}
}

Loading