Custom Authorize Attribute In MVC

  1. //Create A CheckAuthorization.cs File In Your MVC Project  
  2. public class CheckAuthorization: AuthorizeAttribute {  
  3.     //Check Cookie For Unique Field && Check IsAuthenticated Attribute  
  4.     if (HttpContext.Current.Session["UserID"] == null || !HttpContext.Current.Request.IsAuthenticated) {  
  5.         if (filterContext.HttpContext.Request.IsAjaxRequest()) {  
  6.             filterContext.HttpContext.Response.StatusCode = 302; //Found Redirection to another page. Here- login page.             Check Layout ajaxError() script.  
  7.             filterContext.HttpContext.Response.End();  
  8.         } else {  
  9.             filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?ReturnUrl=" +  
  10.                 filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));  
  11.         }  
  12.     } else {  
  13.         //code for page level authorization  
  14.     }  
  15. }  
  16.   
  17.   
  18. //Now, just i have to put [CheckAuthorization] attribute on my controller to access my CheckAuthorization Function which is Custom Authorize Attribute.  
  19.   
  20. //Add authentication mode to Your Web.config  
  21. //Add Below Code To Your Web.confing  
  22. <  
  23. system.web >  
  24.     <  
  25.     authentication mode = "Forms" >  
  26.     <  
  27.     forms loginUrl = "~/Account/Login"  
  28. timeout = "2880" / > //Declare Your Return URL Here. Mean If Login Fail Then Page Redirect This URL  
  29.     <  
  30.     /authentication> <  
  31.     /system.web>