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开发者_如何学C 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
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" });
//...
}
精彩评论