简体   繁体   English

RedirectToRoute 在 ASP.NET MVC 项目中不起作用

[英]RedirectToRoute not working in ASP.NET MVC project

I am building a somewhat complex ASP.NET MVC website with multiple controllers.我正在构建一个带有多个控制器的有点复杂的 ASP.NET MVC 网站。 In the Index()-method/handler of each controller I perform some validation and redirect to the default route in case of an error so the user gets redirected to the default page of the website when something goes wrong.在每个控制器的 Index() 方法/处理程序中,我执行一些验证并在出现错误时重定向到默认路由,以便用户在出现问题时被重定向到网站的默认页面。 However, for some reason the redirect just doesn't work.但是,由于某种原因,重定向不起作用。 I use RedirectToRoute("Default") to redirect to the default route but somehow the Index()-method of the controller I am currently in just gets called again and no redirect is happening.我使用RedirectToRoute("Default")重定向到默认路由,但不知何故,我当前所在的控制器的 Index() 方法只是再次被调用,并且没有发生重定向。 This results in an infinite loop and at some point the browser displays a redirect error.这会导致无限循环,并且在某些时候浏览器会显示重定向错误。 I have the default route defined as follows:我的默认路由定义如下:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults: new { controller = "Home", action = "Index" }

Why does it not redirect to the Index-action of the Home-controller?为什么它不重定向到 Home-controller 的 Index-action?

Because you are redirecting to the same route as you are now.因为您正在重定向到与现在相同的路由。 The defaults that are specified on the "Default" route only apply when there are no values for "controller" and "action", which is not the case - you are running inside a specific action of a controller. “默认”路由上指定的默认值仅适用于“控制器”和“动作”没有值的情况,事实并非如此 - 您正在控制器的特定动作中运行。 Probably what you want is to redirect to the root of your app, which is normally where you go to in the first place (your "Default" route seems to indicate that).可能您想要的是重定向到应用程序的根目录,这通常是您首先访问的位置(您的“默认”路由似乎表明了这一点)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM