在 Route 中带有参数的 RedirectToAction

RedirectToAction with parameters in Route

如果我在路由上没有参数或调用 Id 的参数时,基本上重定向到某些操作时会遇到一些问题,但当我向路由添加一些不同的参数时,RedirectToAction 不起作用,它会抛出错误:路由 table 中没有路由与提供的值匹配。

[Route("First")]
public ActionResult First()
{
    //THIS DOESN'T WORK
    //return RedirectToAction("Second", new { area = "plans"});

    //THIS WORKS
    return RedirectToAction("Third", new { id = "12" });
}

[Route("Second/{area}")]
public ActionResult Second(string area)
{
    return new ContentResult() { Content = "Second : " + area};
}


[Route("Third/{id}")]
public ActionResult Third(string id)
{
    return new ContentResult() { Content = "Third " + id };
}

因此,当我输入 /First 时,它会正确重定向到 Third,但到 Second 时会抛出错误。

我在 RouteConfig 中没有任何额外的东西:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapMvcAttributeRoutes();
}

您可能将 area 参数与 area 路由参数相冲突。 Areas is a resource from Asp.Net MVC 定义如下:

Areas are logical grouping of Controller, Models and Views and other related folders for a module in MVC applications. By convention, a top Areas folder can contain multiple areas. Using areas, we can write more maintainable code for an application cleanly separated according to the modules.

您可以尝试重命名此参数并使用它,例如,尝试将 area 重命名为 areaName:

[Route("First")]
public ActionResult First()
{
    return RedirectToAction("Second", new { areaName= "plans"});
}

[Route("Second/{areaName}")]
public ActionResult Second(string areaName)
{
    return new ContentResult() { Content = "Second : " + areaName};
}