Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyphenated Friendly URL Routing

I'm using ASP.Net MVC Core 2.0 and having a hard time getting routing working for hyphenated friendly URLs. I would like the following URL style:

admin is the area:
    /admin/invoice-categories/new    - Creates a new invoice category
    /admin/invoice-categories/edit/1 - Edits a invoice category
    /admin/invoice-categories        - Shows the invoice categories list

This is my controller code:

[Area("admin")]
[Route("[area]/invoice-categories/"]
class InvoiceCategoriesController {
   public IActionResult New() {}
   public IActionResult Edit(int id) {}
   public IActionResult Index() {}
}

However, this results in an exception stating the "New, Edit, Index" methods in the controller are ambiguous.

Is there a way to get it to work WITHOUT using defining the action name specifically (like HttpGet("New"))?

like image 738
jsmith Avatar asked Mar 07 '23 11:03

jsmith


1 Answers

Unfortunately there isn't a concept of default action in MVC Core attribute routing. Your alternatives are:

  1. Create the route in the middleware where it is possible to specify a default action:

    routes.MapRoute(
        name: "invoice-categories",
        template: "{area}/invoice-categories/{action=Index}/{id?}",
        defaults: new { area = "admin", controller = "InvoiceCategories" });
    
  2. Add an extra route on your Index action:

    [Area("admin")]
    [Route("[area]/invoice-categories/[action]"]
    class InvoiceCategoriesController {
        public IActionResult New() {}
        public IActionResult Edit(int id) {}
    
        [Route("[area]/invoice-categories"]
        public IActionResult Index() {}
    }
    
like image 137
DavidG Avatar answered Mar 15 '23 00:03

DavidG