Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 289
Rana Avatar asked Feb 10 '11 18:02

Rana


1 Answers

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" });
        //...
    }
like image 134
frennky Avatar answered Nov 03 '22 09:11

frennky