Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5: How Does Application_PostAuthenticateRequest() get called in Global.asax?

Tags:

c#

asp.net-mvc

When setting up custom principals for the [Authorize] attribute to work in Microsoft's MVC version 4 and 5, we need to go into Global.asax.cs and set up a method called Application_PostAuthenticateRequest(). I've done that in my current project, and it works just fine.

However, it really bugs me how much this seems like "magic". Application_PostAuthenticateRequest() is not a virtual method. I'm not overloading or implementing any existing method signature in the class. So how does the MVC framework know to call it? C# is a strongly typed language, after all, and you don't get to call a method on a class unless you know it's there.

The only way I can see doing it is via Reflection. Maybe going through the final object's methods and assigning any methods that match a certain signature to delegates. But I really have no idea. And I don't understand why the designers would do that rather than just implementing a virtual method.

So, in summary, (A) how is Application_PostAuthenticateRequest being called when it's not a defined method of the global.asax class, and (B) why didn't they just make it a virtual method?

like image 256
Pharylon Avatar asked Sep 17 '14 17:09

Pharylon


1 Answers

There is a comprehensive article on that by Rick Strahl. In short, the runtime uses reflection on your global application class.

http://weblog.west-wind.com/posts/2009/Jun/18/How-do-ASPNET-Application-Events-Work

This type of event wiring is usually called "automatic" and is also present at page level. For example, the Page_Load is called just because of the default auto wireup.

http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.autoeventwireup(v=vs.110).aspx

like image 172
Wiktor Zychla Avatar answered Oct 02 '22 19:10

Wiktor Zychla