【问题标题】:How does RedirectToRoute work and how to pass data in it?RedirectToRoute 是如何工作的以及如何在其中传递数据?
【发布时间】:2019-06-19 00:33:47
【问题描述】:

我正在尝试重定向到 RecomController 中的路由并且操作是索引,我已经在我的 RouteConfig 文件中定义了路径,并且还指定了我在调用我的 RedirectToRoute 函数时传递的 id 参数。由于某种原因,它找不到该路径。

我还在 RecomController Index 操作上方创建了一个 Route 属性,但它仍然无法将我导航到该路径。我错过了什么吗?

RouteConfig.cs:

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

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
            routes.MapRoute(
            name: "Recomroute",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Recom", action = "Index", id = UrlParameter.Optional }
            );
        }

RecomController.cs:

 [Route("Recom/Index")]
        public ActionResult Index(int id)
        {
         ............//Functioning
        }

调用函数(在另一个控制器中):

ProjectController.cs:

return RedirectToRoute("Recom/Index/{id}", new {id = projectdto.Id });

【问题讨论】:

标签: asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

听起来你在RedirectToRoute() 中使用了错误的路由名称或路径,因此它不起作用:

// this is wrong because first parameter did not match
return RedirectToRoute("Recom/Index/{id}", new {id = projectdto.Id });

对于两个参数重载,需要路由名称(不是路由路径)和路由值,定义如下:

protected internal RedirectToRouteResult RedirectToRoute(string routeName, 
                           RouteValueDictionary routeValues)

因此,您需要提供在RegisterRoutes 中定义的完整路由名称和路由值(例如Recomroute)。

return RedirectToRoute("Recomroute", new {
    controller = "Recom", 
    action = "Index", 
    id = projectdto.Id
});

旁注:

1) 您仍然需要提供controlleractionid 参数才能匹配路由定义。

2) Recomroute 似乎定义在默认路由下方,具有相同的路由段定义,覆盖其下的所有自定义路由,如果您想评估Recomroute,首先将其移至最高顺序并使用不同的路径反对默认路由。

【讨论】:

  • 我试过这种方法,但是还是不行,调试模式由于某种原因跳过了redirectToTRoute函数。
  • @Shad 使用 RedirectToAction() 有什么问题。您对此有何限制?
  • 提供的语法是正确的;但是在RedirectToRoute 启动之前可能会出现问题。我更喜欢在这里使用RedirectToAction("Index", "Recom"),因为您在Recomroute 中的自定义路由路径完全复制了默认路径。
  • 使用 RedirectToAction 的问题是它使用 System.Web.Mvc 干扰我的 [HttpPost] 请求并向我显示错误,另外我还使用 IHttpActionResult 在我的 api 控制器中返回其他内容
  • 请提供您收到的错误消息,这听起来与RedirectToResult 用法不同。 ProjectController 是否包含 [HttpPost] 标记的操作方法,该方法重定向到 /Recom/Index
猜你喜欢
  • 1970-01-01
  • 2014-10-19
  • 2022-11-26
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
相关资源
最近更新 更多