Sliding session for MVC sessions?

I understand with SS services we can do sliding expirations a la…

http://teadriven.me.uk/2013/02/14/sliding-sessions-in-service-stack/

…but what about when using SS authentication (ie a CredentialsAuthProvider) in an MVC project? Is there something that I can override that gets called on each page load? I’m guessing there are several ways, but am wondering what would be the most logical. Maybe a GlobalFilter? Or making a custom base ServiceStackController? Obviously I’d only want it to run for authenticated requests to slide the session expiry.

ServiceStack Request Pipeline is only executed for ServiceStack Requests.

For MVC requests you would need to use their extensibility options, e.g. like using an Action Filter.

Just getting around to working on this. Do you have any tips to point me in the right direction so I can dig further? Should I be looking at changing the IAuthProvider.SessionExpiry or the FormsAuthentication session expiration somehow? I’m not looking to have you do legwork, just need a nudge in the right direction. :slight_smile:

Just retrieving and re-saving the session will update its expiry date again. You’d want to do this in a MVC Response Filter / Filter Attribute. If you inherit ServiceStackController you’ll have access to ServiceStack providers where you can resolve the Session and ServiceStack IHttpRequest. If you have a common base controller with the MVC Filter Attribute attached you should be able to do this automatically for all requests.

Thanks! I had gotten this far so it sounds like I’m almost there…

public class SlideExpirationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var ssController = filterContext.Controller as ServiceStackController<Custom.CustomUserSession>;
        if (ssController == null) return;

        var userSession = ssController.AuthSession as Custom.CustomUserSession;
        if (userSession == null) return;

        base.OnActionExecuting(filterContext);
    }
}

For those in the future who want to implement such a feature, here’s my final code that seems to work great…

public class SlideSessionExpirationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var ssController = filterContext.Controller as ServiceStackController;
        if (ssController == null) return;

        // Get session and re-save to slide/update the expiration date
        var session = ssController.ServiceStackRequest.GetSession();
        if(session != null && session.IsAuthenticated)
            ssController.ServiceStackRequest.SaveSession(session, AppHost.SessionExpiration);
        
        base.OnActionExecuting(filterContext);
    }
}
3 Likes