索引转到示例的 RedirectToAction。com/controller/id

RedirectToAction for index to go to example.com/controller/id

我们正在使用具有 "Index" 操作的控制器:

[Route("")]
[Route("Index/{id:int?}")]
[Route("{id:int?}")]    
public ActionResult Index(int? id)
    {
         var viewModel = new GroupViewModel();
....
        return View("Index", viewModel);

    }

我们可以使用 example.com/my/example.com/my/indexexample.com/my/index/1 来执行此操作。这如我们所愿。现在我们想使用 example.com/my/index/1 语法重定向到这个。

当我们执行这一行时:

return RedirectToAction("Index", "My", new { id = 3 });

它将使用此重定向 url:

example.com/my?id=3

我们希望它改用 example.com/my/index/1

有人知道强制 RedirectToAction 使用不带问号的约定的方法吗?

已于 2017 年 5 月 2 日更新以根据以下评论更正控制器名称

您需要告诉您需要使用哪个路由模板来生成 URL 重定向。目前,您还没有可以生成 URL 的 URL 模板,例如 /my/index/1"My/Index/{id:int?}"

首先,将该路线模板添加到您的操作中,然后像这样设置该路线的 Name 属性:

[Route("")]
[Route("Index/{id:int?}")]
[Route("My/Index/{id:int?}", Name = "MyCompleteRouteName")]
[Route("{id:int?}")]    
public ActionResult Index(int? id)
{
     var viewModel = new GroupViewModel();
....
     return View("Index", viewModel);
}

其次,你必须RedirectToRoute而不是RedirectToActionRedirectToRoute 让您通过给定名称来选择您想要的模板。

所以你必须调用这一行:

RedirectToRoute("MyCompleteRouteName",  new { id = 3 });

而不是

RedirectToAction("Index", "My", new { id = 3 });