Simone Spagna
Simone Spagna

Reputation: 644

Problem with class having as base class ActionFilterAttribute

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.

Upvotes: 0

Views: 181

Answers (1)

holly_cheng
holly_cheng

Reputation: 2481

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

Upvotes: 1

Related Questions