下面的类创建一个名为[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);
}
}
就像现在的实现一样,当我用[SessionTimeout]装饰一个类时,它也会问我构造函数的参数。
如果可能,我想避免这种情况。
有人可以帮我吗? 谢谢。
答案 0 :(得分:1)
HttpContext
是ActionExecutingContext
对象的属性,因此您不需要通过构造函数将其传递给它。这样的事情应该起作用(注意:这未经测试)。
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);
}
}