MVC - 在构造函数中重定向

Dry*_*ods 21 asp.net-mvc asp.net-mvc-3 asp.net-mvc-2

我想知道如果我需要这样做,我如何能够在控制器构造函数内重定向请求?

例如:在构造函数内部我需要使用动态值初始化一个对象,在某些情况下我不想这样做,在这种情况下我想重定向到其他地方.同样,构造函数的其余部分也不会执行"原始跟随操作".

我该怎么做?谢谢

编辑#1

最初我用过:

  public override void OnActionExecuting(ActionExecutingContext filterContext) 
Run Code Online (Sandbox Code Playgroud)

在那里我可以重定向到其他控制器/动作/ url,但是稍后我需要更改我的控制器,我在其构造函数中初始化变量并且有一些代码确实需要重定向请求:P

我也需要这个,因为OnActionExecuting在控制器构造函数之后执行.在我的逻辑中,重定向需要在那里完成.

Dar*_*rov 51

在控制器构造函数内执行重定向不是一个好习惯,因为上下文可能没有初始化.标准做法是编写自定义操作属性并覆盖OnActionExecuting方法并在其中执行重定向.例:

public class RedirectingActionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if (someConditionIsMet)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "someOther",
                action = "someAction"
            }));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后装饰要使用此属性重定向的控制器.要非常小心,不要使用此属性修饰要重定向到的控制器,否则您将遇到无限循环.

所以你可以:

[RedirectingAction]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        // This action is never going to execute if the 
        // redirecting condition is met
        return View();
    }
}

public class SomeOtherController : Controller
{
    public ActionResult SomeAction()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 非常有用的.. 如果“登录会话上下文”为空,我已使用此实现重定向到主页。谢谢达林.. (2认同)