How To Develop Custom Action Filter Attribute In Asp.Net MVC Development

The article is written by Aegissofttech developer in order to share information about creating custom Action Filter Attribute at asp.net MVC development platform. The development team is sharing its experience with global community, so that other country’s developers can learn from them and make best practices of asp.net development.

Develop Custom Action Filter Attribute

MVC Authentication using Filter Attribute:

Create Action Filter class:
An action filter consists of codes that run either before or after an action runs. It can be used for tasks like logging, privileged based authorization, authentication, caching etc.

How to create custom Action Filter Attribute:

  • Create a class “LoginAuthAttribute”
  • Inherit that class with “ActionFilterAttribute, IAuthenticationFilter”
  • Override “OnAuthenticationChallenge” method.
 public class LoginAuthAttribute : ActionFilterAttribute, IAuthenticationFilter  
 {  
 public void OnAuthentication(AuthenticationContext filterContext)  
 {  
 }  
 public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)  
 {  
 var user = filterContext.HttpContext.User;  
 if (user == null || !user.Identity.IsAuthenticated)  
 {  
 filterContext.Result = new HttpUnauthorizedResult();  
 }  
 }  
 }  

You can see above code, the “OnAuthencitcationChallenge” method is overridden, we want to execute this method before any action is executed.

In above code as you can see, we check the user is authenticated or not, if user is not authenticated then we set Result as a UnAuthorisezed result.

Set form authentication mode in web config file as per below code.

 <authentication mode="Forms">  
 <forms loginUrl="~/Login" timeout="2880" />  
 </authentication>  

To use LoginAuthAttribute in our controller we are creating a new BaseController. So, others controller’s is this controller are inherited by this BaseController.

 [LoginAuthAttribute]  
 public class BaseController : Controller  
 {  
 }  

Design Login form.

Create a Login controller and implement login method.

 [HttpPost]  
 public ActionResult Login(LoginModel model, string ReturnUrl)  
 {  
 FormsAuthentication.SetAuthCookie(model.UserName, false);  
 if (Url.IsLocalUrl(ReturnUrl) && ReturnUrl.Length > 1 && ReturnUrl.StartsWith("/")  
 && !ReturnUrl.StartsWith("//") && !ReturnUrl.StartsWith("/\\"))  
 {  
 return Redirect(ReturnUrl);  
 }  
 else  
 {  
 return RedirectToAction("Index", "Home");  
 }  
 }  
 public ActionResult Logout()  
 {  
 FormsAuthentication.SignOut();  
 return RedirectToAction("Index", "Login");  
 }  

Create two method as per above code Login and Logout in Login Controller.

Create a HomeController and inherit this controller with “BaseController”

 public class HomeController : BaseController  
 {  
 }  

Now each and every action methods of Home Controller checks the user is authenticate of not before execute. If user is not authenticate then this will redirect to Login page.

Conclusion:

In the above document we learned how to create custom attribute. Also learned how to use custom attribute with controller in MVC.

Author of this article is working with the Aegissofttech asp.net MVC development team. The post is published by expert to assist global developers and help them in making best development practices. To get more info on related topic, you can contact the Aegis experts anytime, any day, from anywhere. They will get in touch with you soon.

Author bio- Rohit is working with Aegissofttech since long time. Rohit has vast experience is developing asp.net MVC applications for global clients. This article story is published to let other developers know how they can develop a custom action filter attribute and use it for a project.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s