MVC - 在构造函数内重定向
我想知道如果需要的话,如何在控制器构造函数内重定向请求?
例如: 在构造函数内部,我需要使用动态值初始化一个对象,在某些情况下我不想这样做,在这种情况下我想重定向到其他地方。 同样,构造函数的其余部分也不会执行“原始后续操作”。
我该怎么做呢? 谢谢
编辑#1
最初我使用:
public override void OnActionExecuting(ActionExecutingContext filterContext)
在那里我可以重定向到其他一些控制器/操作/url,但后来,我需要更改我的控制器,我在他的构造函数中初始化一个变量并有一些确实需要重定向请求的代码:P
我也需要这个,因为 OnActionExecuting 在控制器构造函数之后执行。 按照我的逻辑,重定向需要在那里完成。
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
EDIT #1
Initially I used:
public override void OnActionExecuting(ActionExecutingContext filterContext)
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
I need this also because the OnActionExecuting executes AFTER the controller constructor.
And in my logic, the redirect needs to be done there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在控制器构造函数内执行重定向不是一个好习惯,因为上下文可能未初始化。标准做法是编写自定义操作属性并覆盖 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:
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.
So you could: