In my asp.net MVC application, in the layout section, there is a combo box that I load the data for it from the session.
I wanted to log out of the user from the session if the session data is null. So I found this class and I added it to my project.
public class SessionExpireAttribute: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var context = filterContext.HttpContext;
HttpContext ctx = HttpContext.Current;
string sessionCookie = context.Request.Headers["Cookie"];
// check sessions here
if (sessionCookie == null)
{
filterContext.Result = new RedirectResult("~/Account/LogOff");
return;
}
base.OnActionExecuting(filterContext);
}
}
And I added at the top of the controllers this attribute.
[HandleError]
[SessionExpire]
public class TaskMainsController : Controller
{
Whenever the session data is null user gets logout from the system and redirected to the login again.
But, In the Layout combo box if session data is null it won't get logout from the system, then session data null exception
triggers. How to avoid this and handle this error?
This application is about to go live but I couldn't found any solution for this matter.
CodePudding user response:
I think you just need to apply this filter all over your project's controllers. To do that, you can add this filter in the GlobalFilters in Global.asax.cs class:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalFilters.Filters.Add(new SessionExpireAttribute());
}
}