C# / .NETDevOpsMisc
C# / .NET
MVC Execute code on each controller method
Alexandru Puiu
Alexandru Puiu
September 16, 2012
1 min

The OnActionExecuting method is fired before every Action in a MVC controller. You can use this method to set and retrieve variables that are useful throughout your session, such as the person’s name, their profile photo, etc.

The following is an example implementation of this method

public class HomeController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext ctx)
    {
        base.OnActionExecuting(ctx);
        using (Repository rep = new Repository())
        {
            if (Request.IsAuthenticated)
            {
                var profile = rep.GetProfileByID((Guid)Membership.GetUser().ProviderUserKey);
                ViewBag.Name = profile.DisplayName;
            }
        }
    }
    public ActionResult Index()
    {
        //your code
        return View();
    }
    //rest of your methods
}

Tags

utils
Alexandru Puiu

Alexandru Puiu

Engineer / Security Architect

Systems Engineering advocate, Software Engineer, Security Architect / Researcher, SQL/NoSQL DBA, and Certified Scrum Master with a passion for Distributed Systems, AI and IoT..

Expertise

.NET
RavenDB
Kubernetes

Social Media

githubtwitterwebsite

Related Posts

RavenDB Integration Testing
Using RavenDB in Integration Testing
December 24, 2022
2 min

Subscribe To My Newsletter

I'll only send worthwhile content I think you'll want, less than once a month, and promise to never spam or sell your information!
© 2023, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media