【问题标题】:How to redirect by common routing如何通过普通路由重定向
【发布时间】:2013-08-31 09:29:26
【问题描述】:

我有行动

public ActionResult Edit(int id)

如果 id 为空,我需要重定向到操作索引。如何在路由中做到这一点?

我试过了:

routes.MapRoute(
                name: "Redirect from empty controller/edit to controller/list",
                url: "{controller}/Edit",
                defaults: new { controller = "Home", action = "Index" }
            );

但它没有帮助。

【问题讨论】:

  • 重定向和路由不是一回事。您希望 Index 操作在没有 id 参数时响应请求,还是要从 Edit 操作向 example.org/MyController/Index url 发送重定向响应?

标签: c# asp.net-mvc routing


【解决方案1】:

重定向很简单。您可以通过将其设置为可空来检查 id 参数是否存在。您不需要路由配置。当用户向http://example.org/Home/Edit发送请求时,这会将用户重定向到http://example.org/Home

public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return RedirectToAction("Index");
    }

    //other logic
}

如果您不想重定向并使索引操作响应带有http://example.org/Home/Edit URL 的请求,您可以创建这样的路由:

routes.MapRoute("HomeEdit", 
                "Home/Edit", new {controller = "Home", action = "Index"});

只要确保该路由高于 RouteConfig 中的默认路由即可。

【讨论】:

  • 重定向我想避免的行为。第二个例子是特殊情况,我需要普通情况。
  • 普通情况下不需要任何东西(example.org/Home/Edit/3)。默认路由会解决这个问题。
  • 我需要 Home/Edit/ -> 重定向到 Home/Index
  • 那你只需要我帖子的第一部分。
【解决方案2】:

嗯,不确定路由,但如果有帮助,您可以使用return RedirectToAction("index", "home");(其中 index 是您的操作方法,home 是您要访问它的控制器)。

【讨论】:

    猜你喜欢
    • 2016-11-22
    • 2019-06-22
    • 2014-03-06
    • 2017-07-25
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    相关资源
    最近更新 更多