5

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

1 Answer 1

7

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" });
        //...
    }
Sign up to request clarification or add additional context in comments.

2 Comments

using this, I will have to use this filer on every methods of every controllers, right? I want to avoid these steps. Basically, If I extend the 'Controller' class as MyController and create all other controllers which extends 'MyController', it should work. Is it a good solution though(i myself tried it yet, looking for experts advice)?
You can use those attributes on controller level like this: [Authorize]public class ReportsController : Controller { }, or register in your Global.asax as global for every controller: protected void Application_Start() { GlobalFilters.Filters.Add(new AuthorizeAttribute()); ... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.