I'm implementing a custom authorize filter that inherits from AuthorizeAttribute. After my research I found out action filters are cached so they are instantiated only once.
Here is my question. If I implement and use a custom action filter like below, it shouldn't work correctly because it would be instantiated once and never call constructor again. But when I tested, it worked well so I'm thinking there is something I don't know.
Can anyone explain this(action filter life cycle?) clearly?
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
private readonly string value = string.Empty;
public CustomAuthorizeAttribute(string value)
{
this.value = value;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// Do something with this.value
}
}
public class HomeController : Controller
{
[CustomAuthorize("ACCESS_INDEX")]
public ActionResult Index()
{
}
[CustomAuthorize("ACCESS_LOGIN")]
public ActionResult Login()
{
}
}
This site has a really good overview of the page lifecycle in MVC
http://blogs.msdn.com/b/varunm/archive/2013/10/03/understanding-of-mvc-page-life-cycle.aspx
The reason your testing showed the filter running all the time is because when ever a route is called from the URL MVC matches it to a controller then an action in that controller. One the action is found MVC sees there is an action filter on it and will execute the action filter first. If two actions are called at the same time (from two different web users) in the same controller two unique instances of the controller is called up so one instance does not know that the other instance has ran the filter.