In this post I am show how to Extended ASP.NET MVC Framework Pipeline with ActionAttribute ,IActionFilter, IResultFilter . First we are going to create new attribute which is derived from ActionAttribute class.
what is Attribute?
Using Attributes we can decorate C# code in declarative fashion. attributes can be applied types, methods, properties, and so forth. Once associated with a program entity, the attribute can be queried at run time using a technique called Reflection.
Attributes exist in two forms: attributes that are defined in the Common Language Runtime's base class library. For example when we are defining a WCF Service Operations we decorate WCF service methods with [OperationContract] attribute.
Second form of attributes are custom attributes that we create, to add extra information to your code. This information can later be retrieved programmatically.So now we are going to create a custom attribute class which is derived from ActionAttribute with the Interfaces IActionFilter, IResultFilter this way i can automatically get the methods which i need to implement.
Here i am going to create attribute called RouteUser and Implementing the OnActionExecuting method this will execute before the Controller Action code executes.
Inside OnActionExecuting method i am going to check if user is Authenticated or not. If user is not Authenticated then i am going to throw an exception called access violation. even you can log the details and Redirect the user to logon page. ok lets do that if user not authenticated we will redirect the user to Logon Page instead of throwing exception [i will put code for both] .
Now we have finished creating the RouteUser attribute let’s use it in our ASP.NET MVC controller action method and test it.
Now let us invoke the Welcome action method browsing the following url http://localhost:49584/Home/Welcome [please browse your local machine URL] with out logging the result is the user Redirected to LogOn Page[http://localhost:49584/Account/LogOn] since the user did not Authenticated.
Note : we can use multiple action filters in the same action method with order number specified so that they execute in that order .
Thanks(Nandri)
SreenivasaRagavan
No comments:
Post a Comment