Search code examples
c#asp.net-core.net-coreasp.net-core-mvcasp.net-core-routing

Setting up routes in ASP.NET Core 3 MVC web app


I have an ASP.NET Core 3 MVC web app and I have a couple of controllers.

I am trying to form my links to access these controllers and I am unsure what I am doing wrong.

Controller names: Exhibitors, DemoQueue

Each controller has an Index action which takes 2 int type parameters

public IActionResult Index(int eventId, int companyId)

And here is my relevant Startup.cs code

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

So it is my understanding that I can browse to these 2 actions by these urls:

Exhibitors/1/2
DemoQueue/3/4

But it seems I have to use this longwinded value:

Exhibitors/Index?eventId=1&companyId=2

Is there a way to set a route to enable me to go to [controller]/id/id ? But go to a different controller e.g. Exhibitors or DemoQueue


Solution

  • You didn't have your custom route template defined. In your startup.cs, all you had was the default routing template.

    To map requests like Exhibitors/1/2 and DemoQueue/3/4 to their corresponding controllers Index method, you need to add the following before the default conventional routing template:

    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "exhibitors-custom",
            pattern: "exhibitors/{eventId:int}/{companyId:int}",
            defaults: new { controller = "exhibitors", action = "index" }
        );
    
        endpoints.MapControllerRoute(
            name: "demoqueue-custom",
            pattern: "demoqueue/{eventId:int}/{companyId:int}",
            defaults: new { controller = "demoqueue", action = "index" }
        );
    
        endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
    
    

    enter image description here

    enter image description here


    Mixed routing

    You can mix the use of conventional routing and attribute routing, but it's typical to use conventional routes for controllers returning HTML for browsers, and attribute routing for controllers serving RESTful APIs.

    Reference: https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1#mixed-routing-attribute-routing-vs-conventional-routing