问题
Is it possible to create a global action filter that will automatically apply to all actions in all controllers in ASP.NET MVC application? I want something like "before_filter" defined in ApplicationController in Ruby on Rails.
Thank you for your help.
回答1:
This really depends what you want to do with it. In many scenarios, the previous answers by vucetica and Adeel will be what you actually want to do. However, neither of them meet the criteria you listed: automatically apply to all actions/controllers.
To do something like that, you would need to implement a handler for the Application BeginRequest event in Global.asax. See the MSDN documentation for more information.
Update - July 27, 2010: ScottGu blogged about MVC 3 Preview 1, which includes a framework for global filters like you're talking about. They're registered via Global.asax, and can apply to all controllers or based on specific criteria.
回答2:
Create your own base controller and inherit from it.
来源:https://stackoverflow.com/questions/3334324/global-action-filter-in-asp-net-mvc