Asp.net mvc 带参数的默认路由

Asp.net mvc 带参数的默认路由,asp.net-mvc,asp.net-mvc-5,Asp.net Mvc,Asp.net Mvc 5,我已经创建了一个控制器,我不希望将默认的操作或视图命名为索引。我在TopicsController中创建了操作,如下所示 [ActionName("Index")] public ActionResult Topics() { var topic = new Topic(); return View("Topics", topic.GetTopics()); } 然后它转到URLxyz.com/Topics 我试图将同样的原理应用到另一个名为ModulesController的控

我已经创建了一个控制器,我不希望将默认的
操作
视图
命名为
索引
。我在
TopicsController
中创建了操作,如下所示

[ActionName("Index")]
public ActionResult Topics()
{
    var topic = new Topic();
   return View("Topics", topic.GetTopics());
}
然后它转到URL
xyz.com/Topics

我试图将同样的原理应用到另一个名为ModulesController的控制器上,但现在我得到了参数

[ActionName("Index")]
public ActionResult Modules(string id)
{
    var topic = new Topic();
    return View("Modules", topic.GetTopics());
}
但现在它在说

找不到资源

我能做些什么使此操作匹配URL,如
xyz.com/Modules/aaaa

要访问URL xyz.com/Modules/aaaa,请将
模块的
操作
名称更改为
aaaa
,如下所示:

[ActionName("aaaa")]
public ActionResult Modules(string id)
{
    var topic = new Topic();
    return View("Modules", topic.GetTopics());
}
routes.MapRoute(
    name: "Modules",
    url: "{controller}/{action}/{id}",
    defaults: new { controller="Modules", action="Modules", id=UrlParameter.Optional }
    );
仅供参考-最好避免使用
ActionName
过滤器命名每个操作。在某种程度上,这将变得难以管理。而是在
RouteConfig
中管理路由,如下所示:

[ActionName("aaaa")]
public ActionResult Modules(string id)
{
    var topic = new Topic();
    return View("Modules", topic.GetTopics());
}
routes.MapRoute(
    name: "Modules",
    url: "{controller}/{action}/{id}",
    defaults: new { controller="Modules", action="Modules", id=UrlParameter.Optional }
    );
以下URL适用于上述路由:

  • xyz.com/Modules/aaaa
  • xyz.com/Modules/aaaa/123
  • xyz.com/Modules/aaaa?id=123
更新: 如果希望“aaaa”作为参数并希望使用xyz.com/Modules/aaaa访问操作(其中“aaaa”将作为
Id
变量的值绑定),则将以下路由添加到路由表中:

routes.MapRoute(
    name: "Modules",
    url: "Modules/{id}",
    defaults: new { controller="Modules", action="Modules", id=UrlParameter.Optional }
    );

注意上面
Url
的值。

我希望
aaaa
是参数名而不是操作名。我不能只执行
ActionName/parameterName
并默认获取操作名吗?@Imad是的,您可以这样做。我已经更新了答案。嘿,很抱歉再次打扰你,我们可以使用基于属性的路由来完成吗?因为使用这种方法,我的路由变得相当大。@Imad,请将以下内容添加到操作:
[Route(“Modules/{id}”)]
并删除
ActionName
过滤器。