当前位置 : 主页 > 编程语言 > c语言 >

c# – 连字符友好URL路由

来源:互联网 收集:自由互联 发布时间:2021-06-25
我正在使用ASP.Net MVC Core 2.0并且很难获得用于连字符友好URL的路由.我想要以下网址样式: admin is the area: /admin/invoice-categories/new - Creates a new invoice category /admin/invoice-categories/edit/1 - Edits
我正在使用ASP.Net MVC Core 2.0并且很难获得用于连字符友好URL的路由.我想要以下网址样式:

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

这是我的控制器代码:

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

但是,这会导致异常,说明控制器中的“新建,编辑,索引”方法不明确.

有没有办法让它工作而不使用特定的动作名称(如HttpGet(“新”))?

遗憾的是,MVC Core属性路由中没有默认操作的概念.您的替代方案是:

>在中间件中创建可以指定默认操作的路径:

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

>在Index操作上添加额外路线:

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

    [Route("[area]/invoice-categories"]
    public IActionResult Index() {}
}
网友评论