[英]Problem with class having as base class ActionFilterAttribute
The following class creates a custom action filter named [SessionTimeout]:以下 class 创建了一个名为 [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.由于现在的实现,当我 go 用 [SessionTimeout] 装饰 class 时,它还会询问我构造函数的参数。
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. HttpContext
是ActionExecutingContext
object 的一个属性,因此您不需要通过构造函数将其传递给它。 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.