MVC - 重定向的内部构造 [英] MVC - Redirect inside the Constructor

查看:130
本文介绍了MVC - 重定向的内部构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我怎么能够请求重定向控制器构造函数中,如果我需要做呢?

I would like to know how am I able to redirect the request inside the controller constructor if I need to do it?.

例如:
构造函数中,我需要用动态值初始化对象,在某些情况下,我不想这样做,并在这种情况下,我想重定向到其他一些地方。
在以同样的方式构造的其余部分将不被执行,无论是原创以下行动。

For example: Inside the constructor I need to initialize an object with an dynamic value, in some cases I don't want to do it and in that case I want to redirect to some other place. At the same way the rest of the constructor will not be executed neither the "original following action".

我该怎么办呢?
谢谢

How can I do it? Thank you

编辑#1

起初我用:

  public override void OnActionExecuting(ActionExecutingContext filterContext) 

有我可以重定向到其他一些控制器/动作/ URL,但后来的时候,我需要改变我的控制器,在那里我在他的构造函数初始化变量,有一些code,真正需要重定向请求:p

There I could redirect to some other controller/action/url, but later in time, I needed to change my controller, where I initialize an variable in his constructor and have some code that really needs to redirect the request :P

我需要这也是因为OnActionExecuting执行控制器构造函数之后。
而在我的逻辑,重定向需要在那里进行。

I need this also because the OnActionExecuting executes AFTER the controller constructor. And in my logic, the redirect needs to be done there.

推荐答案

执行控制器构造函数中的重定向是不是一个好的做法,因为上下文可能不被初始化。标准的做法是写一个自定义操作属性,并覆盖<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute.onactionexecuting.aspx\">OnActionExecuting方法和内部执行重定向。例如:

Performing redirects inside the controller constructor is not a good practice because the context might not be initialized. The standard practice is to write a custom action attribute and override the OnActionExecuting method and perform the redirect inside. Example:

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

再装点您希望与此属性重定向控制器。格外小心,不要来装点你重定向到与此属性控制器或你要碰上死循环。

and then decorate the controller which you would like to redirect with this attribute. Be extremely careful not to decorate the controller you are redirecting to with this attribute or you are going to run into an endless loop.

所以,你可以:

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

这篇关于MVC - 重定向的内部构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆