Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add code to run before any view? Equivalent to Masterpage pageload?

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.

like image 634
billy jean Avatar asked Dec 20 '25 06:12

billy jean


2 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.

like image 79
Tridus Avatar answered Dec 23 '25 01:12

Tridus


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

like image 20
Kenny Eliasson Avatar answered Dec 23 '25 00:12

Kenny Eliasson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!