Introduction
In this example, showing how to use and validate session (HttpContext.Current.Session) in MVC application. In my earlier article, one of more secured feature to keep up your website healthy cross-site request forgery explained. MVC application has provided us facility to apply filter like- Authorization
- Action Filter
- Result Filter
- On Error Filter
Add below code in FilterConfig.cs under App_Start folder
This code is written under OnActionExecuting in FilterConfig.cs file
public class UserSessionActionFilter : ActionFilterAttribute, IActionFilter { public override void OnActionExecuting(ActionExecutingContext filterContextORG) { HttpContext ctx = HttpContext.Current; if (HttpContext.Current.Session["User"] == null) { /// this handles session when data is requested through Ajax json if (filterContextORG.HttpContext.Request.IsAjaxRequest()) { JsonResult result = new JsonResult { Data = "Session Timeout!" }; filterContextORG.Result = result; } else { /// If session is expired then redirected to logout page which further redirect to login page. filterContextORG.Result = new RedirectResult("~/Main/Home/Logout"); return; } } }
In Global.asax Should register FilterConfig.cs
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); }
Checking Session is expired or not
We have to call action attribute [UserSessionActionFilter] in MVC controller to check whether session is preserving or not. If session is expired it will throw to other page.[UserSessionActionFilter] public ActionResult ContactDetail() { return View(); }
Thank you . its fantastic.
ReplyDelete