Search code examples
c#asp.net-coreasp.net-mvc-routing

How do I configure routing with two optional route values?


This is my route config in Startup.cs:

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

Some of my views make use of both id and tab, some just id and some just tab.

id is of type Guid, and tab is of type int.

How can I configure my routing to eliminate the id-part (/0) in the following url to a view which does not make use of it?

/Home/Index/0/3 // id is not relevant, tab = 3

In this case, I have to set id to 0 in order for the url to work. This is an index-view with sub sections organized in tabs.


Solution

  • For this you can do something like. As per your comment Id is guid and tab is int.

    app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                      name: "onlyid",
                      pattern: "{controller=Home}/{action=Index}/{id:guid}", new { tab = default(int) });
    
                    endpoints.MapControllerRoute(
                       name: "onlytab",
                       pattern: "{controller=Home}/{action=Index}/{tab:int}", new { id = default(Guid) } );
    
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id:Guid}/{tab:int}");
                });
    

    Now if there is only tab then onlyTab will get choose and it has default value for Guid ( Guid.Empty) but you can address like /Home/Index/1 .

    If there is only id then onlyId will get selected and it has default value for integer. Home/Index/yourguid

    If you pass both then third route get selected.

    Method as Controller look like following.

     public IActionResult Index(Guid? id,int? tab)
            {
                return Ok(new { Id = id, Tab = tab });
            }