类具有作为基本类的ActionFilterAttribute的问题

时间:2019-11-15 21:27:49

标签: c# asp.net-core actionfilterattribute

下面的类创建一个名为[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]装饰一个类时,它也会问我构造函数的参数。

如果可能,我想避免这种情况。

有人可以帮我吗? 谢谢。

1 个答案:

答案 0 :(得分:1)

HttpContextActionExecutingContext对象的属性,因此您不需要通过构造函数将其传递给它。这样的事情应该起作用(注意:这未经测试)。

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);
    }
}