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 all 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
2 changes: 2 additions & 0 deletions docs/header_names/allowed_framework_names.adoc
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// C#
* ASP.NET
* ASP.NET Core
* ASP.NET MVC 4.x

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See also #3668

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to https://dotnet.microsoft.com/en-us/platform/support/policy/aspnet asp.net mvc 4.x is no longer supported.

Are we sure we want to support it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's true I think there has been maybe some confusion.
@antonioaversa @martin-strecker-sonarsource maybe we should review the two rules we merged already?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 4.x in "Asp.MVC 4.x" refers to the 4 in e.g. .Net Framework 4.8. The term is taken from this website:
https://learn.microsoft.com/en-us/aspnet/core/
It links to the documentation for the ASP MVC releases for the old .Net Framework 4.8. This includes ASP.NET MVC 5 which is still in support. So by referring to "Asp.MVC 4.x " we refer to "ASP.NET MVC 5"
I know this is highly confusing, but something we discussed with Denis and concluded is the best solution.

* Razor
* .NET
* Entity Framework Core
Expand Down
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 to avoid unpredicted behavior. As such, the controller should exclude itself from conventional routing by applying a `[Route]` attribute.

== 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.

antonioaversa marked this conversation as resolved.
Show resolved Hide resolved
[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();
}
----

== How to fix it in ASP.NET Core

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 defined, you should specify a route template on the controller with the https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.routeattribute[`RouteAttribute`] as well.

=== 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/aspnet/core/mvc/controllers/routing#mixed-routing-attribute-routing-vs-conventional-routing[Mixed routing: Attribute routing vs conventional routing]
* 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 or RouteAttribute is specified at an action level.

=== Highlighting

* Primary location: Controller class declaration identifier
* Secondary location: The identifier of 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": "A Route attribute should be added to the controller when a route template is specified at the action level",
"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