Sunday, 2 August 2015

MVC: Controllers


Action Filters
- apply pre and post processing logic to a controller action and its result.
- components that you want to apply cross cutting logic - the logic that has to execute across multiple controller actions but you don't want to duplicate code inside of individual controllers.

  • OutputCache
         - tells the runtime that it's allowed to cache the final output of some action and to use that cached result to service future requests.
  • ValidateInput
        - turn off request validation and allow dangerous input
  • Authorize
         - allows you to ensure a user is logged in and perhaps in a specific role like an admin.

        [Authorize (Roles="Admin")]
        or

        [Authorize]
        public ActionResult Search(string name = "French")
        {
               var message = Server.HtmlEncode(name);
               return Content(message);
         }
         - which means a user has to be logged in for him to be able to use the search action. You'll be redirected to a login screen if you're not logged in.

        Action filter can also be placed on a controller to apply to all the functions within the Controller class.
         [Authorize]
        public class CuisineController : Controller
         {
                   public ActionResult Search(string name = "French")
                  {
                         var message = Server.HtmlEncode(name);
                          return Content(message);
                   }
          }

  • ValidateAntiForgeryToken
       - helps prevent cross site request for forgeries
  • HandleError
       - can specify a view to render in the event of an unhandled exception


Global Filters
- typically registered during application start in Global.asax.cs.

protected void Application_Start()
{
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}

RegisterGlobalFilters is inside FilterConfig.cs under App_Start folder.

public static RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}
HandleErrorAttribute - will be in effect for every single request that is processed by any controller inside of your application. Its purpose is to display friendly error page to users when something goes wrong.

No comments:

Post a Comment