简体   繁体   English

ASP.NET MVC Controller中的执行顺序是什么?

[英]What is the order of execution in ASP.NET MVC Controller?

Say I have a controller called "HomeController" which inherits from Mvc.Controller. 假设我有一个名为“ HomeController”的控制器,该控制器继承自Mvc.Controller。 Also say I have written the constructor of the controller and some filters for some actions. 还说我已经写了控制器的构造函数和一些动作的过滤器。

Public Class ClientController
    Inherits System.Web.Mvc.Controller

    Public Sub New()
        ''Some code
    End Sub

    <SomeActionFilter()> _
    Function Index() As ActionResult
        Return View()
    End Function
End Class

My questions are : 我的问题是:

  1. What is the order of execution of constructor, filter, action? 构造函数,过滤器,动作的执行顺序是什么?
  2. Can I have a filter for the Constructor, if I do not want to run the code in it by checking for some conditions? 如果我不想通过检查某些条件在其中运行代码,可以为构造函数使用过滤器吗?

Constructor will go first. 构造函数将优先。 Depending on the type of filter that either the filter or action method will execute second. 根据过滤器的类型,过滤器或操作方法将在第二次执行。 See here for the filter types . 有关过滤器类型,请参见此处。

Filter doesn't intercept constructor. 过滤器不会拦截构造函数。 If you want to control the constructor invocation of Controller, you need to build a custom controller factory by implementing IControllerFactory (or DefaultControllerFactory ) and register it with ControllerBuidler , eg: ControllerBuilder.Current.SetControllerFactory(typeof(MyControllerFactory)) on application start. 如果要控制Controller的构造函数调用,则需要通过实现IControllerFactory (或DefaultControllerFactory )来构建自定义控制器工厂,并在ControllerBuidler注册它,例如:在应用程序启动时ControllerBuilder.Current.SetControllerFactory(typeof(MyControllerFactory))

if I do not want to run the code in it by checking for some conditions? 如果我不想通过检查某些条件来在其中运行代码?

Can't you write that code directly in the constructor (eg the check condition in the base controller to reuse)? 您不能直接在构造函数中编写该代码(例如,要重用的基本控制器中的检查条件)吗? Why do you need a filter in this case? 为什么在这种情况下需要过滤器?

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

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