-
Couldn't load subscription status.
- Fork 10.5k
Attribute routing and MapGroup() #63668
-
Let's consider following program:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseRouting();
app.MapGroup("Group")
.MapControllerRoute(name: "default",
pattern: "Home/Conventional",
defaults: new { controller = "Home", action = "Conventional" });
app.Run();
public class HomeController : Controller
{
public IActionResult Conventional()
{
return Content("Conventional");
}
[Route("/Home/Attribute")]
public IActionResult Attribute()
{
return Content("Attribute");
}
}
I have one controller that mixes both conventional (albeit "fixed") and attribute routing.
Could someone give me hints why following works:
$ curl -i http://localhost:5090/Group/Home/Attribute
HTTP/1.1 200 OK
Content-Length: 9
Content-Type: text/plain; charset=utf-8
Date: 2025年9月13日 08:48:30 GMT
Server: Kestrel
Attribute%
Suddenly attribute route is attached to a group. Is there a way to prevent it?
Background: I want to create conventional routing similar to Rails resources and group them with MapGroup(). However still I have still some attribute routed controllers and they got attached to various groups.
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 2 replies
-
Hello @MichalSznajder,
this is the expected behavior. MapControllerRoute() maps both conventional and attribute routing controller actions.
When you call it on a route group, the group’s prefix is applied to all endpoints it adds /Group/Home/Attribute works.
To prevent it, you have to map attribute routes outside the group and only put conventional routes in the group:
app.UseRouting(); app.MapControllers(); // attribute-routed controllers (no group) app.MapGroup("/Group") .MapControllerRoute("fixed", "Home/Conventional", new { controller = "Home", action = "Conventional" });
This keeps attribute-routed actions from inheriting the group prefix
Beta Was this translation helpful? Give feedback.
All reactions
-
I tried this solution and attribute controllers are mapped both in group and "at root":
$ curl -i http://localhost:5090/Home/Attribute
HTTP/1.1 200 OK
Content-Length: 9
Content-Type: text/plain; charset=utf-8
Date: 2025年9月14日 08:54:55 GMT
Server: Kestrel
Attribute%
$ curl -i http://localhost:5090/Group/Home/Attribute
HTTP/1.1 200 OK
Content-Length: 9
Content-Type: text/plain; charset=utf-8
Date: 2025年9月14日 08:54:57 GMT
Server: Kestrel
Attribute%
This solution was suggested by AI and I think also found it on some websites.
I wonder if this is a bug in net8 or general issue.
Beta Was this translation helpful? Give feedback.
All reactions
-
I just tried on 10.0.100-rc.1.25451.107 but it is the same. On osx but it should not matter.
Beta Was this translation helpful? Give feedback.