10

Can someone explain why the authorize attribute lifecycle appears to be managed relative to the class or method it is applied to? This is as opposed to be managed relative to the request lifecycle.

If I decorate a controller at the class level the authorize attributes constructor only gets called once across multiple requests to the same controller. If I decorate each controller method then I get new authorize attribute constructor calls for each controller method called.

What's this behavior all about? I would expect the authorize attribute creation to happen every request.

Daniel
  • 101
  • 3
  • How are you determining that it's only called once when applied to the class? AFAIK, the controller is instantiated and destroyed with each request. It kind of *has* to be, or you'd end up with cross-request pollution. It's possible that when debugging in Visual Studio that it circumvents this for some reason, but if you're ending up with the same controller instance for every request on real IIS, then there's a problem. – Chris Pratt Sep 27 '13 at 18:17
  • Chris, I wasn't talking about the controller's lifecycle. Rather, I'm asking about the lifecycle of the AuthorizeAttribute. The AuthorizeAttribute is not created for every request, and I expected it to be. Unfortunately, that lead to some issues for this current application because we have to modify the Roles at runtime. – Daniel Oct 13 '13 at 20:19

1 Answers1

11

ASP.NET MVC will cache ActionFilters and try to reuse them on subsequent requests. The actual authorization will occur on each request but the contructor will only get called on the first. You should not maintain any internal state in an ActionFilter.

Mark Olsen
  • 939
  • 7
  • 10