【问题标题】:ASP.NET MVC RedirectToAction not redirecting to Index of another controllerASP.NET MVC RedirectToAction 未重定向到另一个控制器的索引
【发布时间】:2017-05-18 08:48:03
【问题描述】:

在我的帐户/登录控制器方法中,我有类似的内容:

var classA = GetObject(); //actual code omitted
switch(classA.PropA)
{
    case 1:
        return RedirectToAction("Action2", "Registration");
    //more case code omitted
    default:
        return RedirectToAction("Index", "Registration");
}

所有情况在 switch 块中都可以正常工作,除了默认情况下它应该转到 RegistrationController 中的索引。取而代之的是,它会将我带到 localhost:port/Registration,其中省略了操作索引。

如果将 ActionName 更改为其他名称(例如 Index2),它会正常工作。如果将控制器名称更改为其他名称,也可以正常工作。

RouteConfig 是 只是创建项目时自动生成的代码,如下:

    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 }
        );
     }

提前致谢。

【问题讨论】:

  • RedirectToAction("Index", "Registration"); 执行时会发生什么?
  • 抱歉,我确实忘记提及了。它只是转到 localhost:port/Registration
  • 你是否在 Index 操作方法上放置了调试器?
  • 它根本没有进入注册/索引
  • 如果你输入localhost:port/Registration/index然后呢?

标签: c# asp.net-mvc redirecttoaction


【解决方案1】:

路由设置没有问题,原因是它在URL中不包含Index,因为根据default route

url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

当您输入/Registration 时,路由已经知道默认操作是index,因此它不会在URL 中添加/index 以及关于

403.14 禁止

如果您查看此帖子HTTP Error 403.14 - Forbidden - MVC 4 with IIS Express,可能是因为您的项目目录中可能有一个名为Registration 的文件或文件夹

【讨论】:

  • 这绝对是正确的!谢谢!
  • @ChenChen 如果有帮助,你可以接受我的回答 :) 如果你不知道如何查看这个How to accept an answer
  • @ChenChen 没问题 :)
【解决方案2】:

如果您使用RedirectionToAction("Index","ControllerName"); 它将使用默认映射配置将您重定向到localhost:port/ControllerName 在您的情况下,如果您执行 RedirectionToAction("Index","ControllerName"); 它会将您重定向到 localhost:port/Registration

【讨论】:

  • 这清楚了很多事情。谢谢。但是,“注册”是保留字还是什么?当我收到“HTTP 错误 403.14 - 禁止 Web 服务器配置为不列出此目录的内容”时,该控制器而不是任何其他控制器
【解决方案3】:

尝试使用

return RedirectToAction("Index");

在 RouteConfig 中,您可以将操作“索引”路由到控制器“注册”

喜欢

routes.MapRoute("Index", "Index", new { controller = "Registration", action = "Index" });

【讨论】:

  • 您还应该在 RouteConfig 中验证此代码。 routes.MapRoute("Registration", "Registration/{action}/{id}", new { controller = "Registration", Action = "Index", id = UrlParameter.Optional });
猜你喜欢
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
相关资源
最近更新 更多