Rana
Rana

Reputation: 6154

Where To Implement Common functionality In Asp.net MVC

I am learning Asp.net MVC 3. Just wondering, is there any way to define a method that will be executed before executing any other methods of any controllers? That means it should work like the constructor of base "Controller" class.

This will include some common functionality like checking user session/if not logged in redirect to login page, otherwise set some common values from db that will be used everywhere in the application. I want to write them only once, don't want to call a method on each controller methods.

Regards

Upvotes: 5

Views: 808

Answers (1)

frennky
frennky

Reputation: 13934

That's what action filters are for. There are some already build in framework, like AuthorizeAttribute:

        [Authorize(Roles = "Admins")]
        public ActionResult Index()
        {
            return View();
        }

Edit:

Filters can be set on actions, controllers or as global filters.

[Authorize(Roles = "Admins")]
public class LinkController : Controller
{
    //...
}

Inside Global.asax

    protected void Application_Start()
    {
        GlobalFilters.Filters.Add(new AuthorizeAttribute { Roles = "Admins" });
        //...
    }

Upvotes: 7

Related Questions