gpt4 book ai didi

c# - ASP.NET MVC : What is the correct way to redirect to pages/actions in MVC?

转载 作者:IT王子 更新时间:2023-10-29 04:14:45 25 4
gpt4 key购买 nike

我是 MVC 的新手,但不确定究竟是哪个重定向...替换 WebForms 中使用的标准重定向是标准的 Response.Redirect()

例如,我需要在几个场景中重定向到其他页面:

  1. 当用户注销时(操作中的表单注销​​)我想重定向到登录页面。
  2. 在 Controller 或基本 Controller 事件中,例如Initialize,我想重定向到另一个页面(AbsoluteRootUrl + Controller + Action)

似乎在某些情况下调用多个重定向会导致错误,这与页面已经被重定向有关吗?如何取消当前请求,只重定向?

更新:

这个问题的答案 ( System.Web.Mvc.Controller Initialize ) 表明不应该使用 Initialize 而应该使用 OnActionExecuting 吗?

关于为什么不应该使用 Initialize 或为什么 OnAuthorization 不是更好的选择的任何评论?

更多信息:

这篇博文 ( http://blog.wekeroad.com/blog/aspnet-mvc-securing-your-controller-actions/ ) 表明 OnActionExecuting 对身份验证很有用(如上面的链接所示)我想将它添加到 Controller 基类中的那个事件就可以了,因为每个页面在 MVC 中运行一个 Action,所以应该不会有太大区别,并且具有重定向的能力应该更容易。这确实有道理,但对我来说似乎也有道理,事情可以在这个事件之前的事件中完成,让我们质疑这些事件的目的是什么?将给予 OnActionExecuting 一个机会..

最佳答案

1) 当用户注销时(操作中的表单注销​​)我想重定向到登录页面。

public ActionResult Logout() {
//log out the user
return RedirectToAction("Login");
}

2) 在 Controller 或 Base Controller 事件中,例如 Initialze,我想重定向到另一个页面(AbsoluteRootUrl + Controller + Action)

为什么要从 Controller 初始化重定向?

路由引擎会自动处理传入的请求,如果你想从 Controller 上的索引操作重定向,只需执行以下操作:

public ActionResult Index() {
return RedirectToAction("whateverAction", "whateverController");
}

关于c# - ASP.NET MVC : What is the correct way to redirect to pages/actions in MVC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2677072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com