9

I wrote a attribute route Route("Home/{category?}/{Subcategory?}/List") want to match the following examples /Home/C1/S1/List, /Home/C1/List, /Home/List

But only to match the first url, the optional parameter did not work. How to use a routing rule matches the above three examples?

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [Route("Home/{category?}/{subcategory?}/List")]
    public IActionResult List(Category? category = null, SubCategory? subcategory = null)
    {
        return Content(category.ToString() + "/" + subcategory.ToString());
    }

    [Route("Home/{code}/Detail")]
    public IActionResult Detail(string code)
    {
        return Content(code);
    }
}


public enum Category
{
    C1,
    C2,
    C3,
    C4
}

public enum SubCategory
{
    S1,
    S2,
    S3,
    S4
}

Similar Questions

Routing optional parameters in ASP.NET MVC 5

MVC routing with one fixed action and controllers with multiple optional parameters

Community
  • 1
  • 1
jiangzm
  • 371
  • 1
  • 2
  • 6
  • 1
    Optional parameters should be in the last. You cannot insert optional parameters between the non-optional parameters as you did in the List action. – Sometimes Code Jun 02 '16 at 05:35

2 Answers2

18

If a route does not work, it can be done using three routing rules.

[Route("Home/List")]
[Route("Home/{category}/List")]
[Route("Home/{category}/{subcategory}/List")]

thx all.

jiangzm
  • 371
  • 1
  • 2
  • 6
5

You may only have one optional parameter per route, and that optional parameter must be the last parameter.

see https://exceptionnotfound.net/asp-net-core-demystified-routing-in-mvc/

Michal Zemek
  • 81
  • 2
  • 3