如何在 ASP.NET MVC 中使用没有参数名称的自定义路由?

How to have a custom route without parameter names in ASP.NET MVC?

我的方法有以下路线:

[HttpGet]
[Route("Company/Employees/{name}")]
public ActionResult Details(string name)

我想通过向

发出请求来访问姓名为 属性 "John" 的员工
Company/Employees/John

但现在这条路线只有在我输入以下内容时才有效:

Company/Employees?name=John

我该如何解决这个问题?

编辑:

这是我的路线配置(区域内)

context.MapRoute(
            "Company_default",
            "Company/{controller}/{action}/{id}",
            new { controller = "Employees", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "MySite.Areas.Company.Controllers" }
        );

正如我已经说过的,您的默认路由与您的自定义 Contoller 路由具有相同的结构。因为 {id} 参数是 可选的 .

如果你想使用你的路线,你应该在你的默认路线之前在你的 RouteConfig 中定义自定义路线,并摆脱你的 Route 控制器上的属性:

context.MapRoute(
            "DetailsCustom",
            "Company/Employees/{name}",
            new { controller = "Employees", action = "Details"},
            namespaces: new[] { "MySite.Areas.Company.Controllers" }
        );

在您的其他路线之前添加:

context.MapRoute(
        "Company_default",
        "Company/{controller}/{id}",
        new { controller = "Employees", action = "Index", id =    UrlParameter.Optional },
        namespaces: new[] { "MySite.Areas.Company.Controllers" }
    );

因为你的前一个选择 "John" 作为 "action" 参数