-
Notifications
You must be signed in to change notification settings - Fork 29
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
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
ed93413
first rule draft
mary-georgiou-sonarsource d28c5ae
add UTs
mary-georgiou-sonarsource fd3d3ba
Re-work the description
martin-strecker-sonarsource 43ad874
Add missing "options" introduction
martin-strecker-sonarsource 137814a
Re-work metadata json
martin-strecker-sonarsource 2aa0f0b
Add rspecator-view
martin-strecker-sonarsource 8e0cb83
Improve code comment
martin-strecker-sonarsource 55359be
Improve conventional routing route
martin-strecker-sonarsource fc5638f
Newline
martin-strecker-sonarsource 9d453c6
Apply suggestions from code review
martin-strecker-sonarsource 075752e
Add ASP.Net Core header
martin-strecker-sonarsource 54d4737
Add link
martin-strecker-sonarsource f72af7a
Change title
martin-strecker-sonarsource b252250
Remove UT file
martin-strecker-sonarsource c24ef6b
Code review changes
antonioaversa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
* Razor | ||
* .NET | ||
* Entity Framework Core | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
{ | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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[] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
} | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
See also #3668
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.