The following class creates a custom action filter named [SessionTimeout]:
public class SessionTimeoutAttribute : ActionFilterAttribute
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ISession _session;
public SessionTimeoutAttribute(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
_session = _httpContextAccessor.HttpContext.Session;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = _httpContextAccessor.HttpContext;
if (!ctx.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult("~/Account/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
As the implementation is now, when I go to decorate a class with [SessionTimeout] it also asks me the parameter for the constructor.
I would like to avoid this if possible.
Can someone helè me? Thanks.
HttpContext
is a property of the ActionExecutingContext
object, so you shouldn't need to pass it into via the constructor. Something like this should work (note: this is not tested).
public class SessionTimeoutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = filterContext.HttpContext;
if (!ctx.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult("~/Account/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}