Action Filters in ASP.NET,MVC


In a ASP.NET MVC Application ,Controllers have action method which include all the code
which executes a request ,for eg , when a user clicks on a link or clicks on a submit button,
the corresponding controller is called,which than routes the control to the action method
associated to it
Lets have a look at the following C# code below

public class MainController : Controller
{
    public ActionResult Index()    {
        ViewData["Message"] = "here is your first MVC Application ,, have a good leaning session ";
        return View();
    }
    public ActionResult About()    {
        return View();
    }
}

Here you see there is a Controller named MainController which have Index() and About() as
the  two of the action methods . Action Methods describe what will happen next . Say if
the control is passed on to Index() action Method , there will be a View rendered with
the message as shown above .
Pretty Straight ,isnt it .. Well now lets continue further . Suppose now we want to add
some logic say before the action Method is called or after the action method runs , than
how do we achieve that .? In this Kind os situation MVC came up with something called as
Action Filters

Action Filters are Attributes which help to perform a certain logic in a application .
Say we have a website of a Bank and a User enters his credentials before loggin in
and than hits the submit button . Here the controller comes into the picture , which handles
the request , authorises whether he input is correct and than gives the user all the controls
Here the Authorization is done by using a Filter Attribute called as [Authorize]

For eg ,
[Authorize]
public class MainController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "here is your first MVC Application ,, have a good leaning session ";
        return View();
    }
    public ActionResult About()
    {
        return View();
    }
}
Here [Authorize] Action filter does all kind of Validation and Authentication for that User
There are few more Filter in MVC , let just quicky go through those as well
[HandleError]--This attribute does all exception handling for that particular action method
[OutputCache]--Basically helps in the performance of an MVC Application by caching the output
               to the Memory ,which in turn saves time and resources
[validateAntiForgeryToken]---Prevents Cross site scripting attacks

One can also create custom action filter by using ActionFilterAttribute class

No comments:

Post a Comment