What might be the equivalent to a MasterPage code-behind page load in MVC? I want to check if a user is logged in my local app or facebook or twitter before every view is returned.
4 Answers
Couple of options.
Create a base controller and use it's initialize method. Have your other controllers inherit it. This is probably closest to how a code behind in a MasterPage used to work.
public abstract class BaseController : Controller
{
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
       //Do Stuff
    }
}
That's the method I use for code that I want run before any Views, and for code that sets things up in the Layout view (ie: the layout stuff that's used on every page).
Alternately Global.asax is still supported, you could use Application_BeginRequest or Application_PostAcquireRequestState.
 
    
    - 5,021
- 1
- 19
- 19
- 
                    1Application_BeginRequest, I don't think this lets you check the logged in state i.e. (Request.IsAuthenticated) for some reason. So this does not work. – philbird Apr 02 '12 at 06:44
Use ActionFilters instead. In the framework there already is a Authorization filter. Inherit it and bend it to your will.
Read more about action filters here
 
    
    - 2,047
- 15
- 23
Are you using a master page?
If so, just add a call to your code in there (keep it to just a method call and implement the logic in another class).
Alternatively, derive a new View class from System.Web.UI.View, override the OnPreRender or OnLoad event and use that as the base class for your own views.
 
    
    - 12,978
- 2
- 40
- 49
Use a partial view and include it in your master page / layout.
You can combine this with a partial action too, see here - asp.net MVC partial view controller action
The default mvc3 vstudio template contains a _logonpartial file in the views/shared directory that may be a good starting point for you
 
     
     
    