会话超时未点击操作过滤器

时间:2018-08-06 03:37:30

标签: c# asp.net-mvc httpsession

我已在Startup.Auth.cs中启用了会话超时:

 app.UseCookieAuthentication(new CookieAuthenticationOptions
 {
       ExpireTimeSpan = TimeSpan.FromMinutes(1)
 }

将其设置为1分钟进行测试。现在,我创建了一个动作过滤器:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;


        base.OnActionExecuting(filterContext);
    }
}

并通过添加FilterConfig.csfilters.Add(new SessionExpireFilterAttribute());中注册。我还将属性[SessionExpireFilter]放在了customercontroller类上。

现在发生的事情是,如果在会话终止时我单击向操作customer/edit发送请求的按钮,则代码确实会在customercontroller constructor中达到断点然后返回200。它永远不会达到actionfilter中的断点。它也从未达到实际动作edit

有什么想法吗?

谢谢。

1 个答案:

答案 0 :(得分:2)

从HTTP标头中删除Cache-Control

防止在MVC中进行缓存,我们创建了自己的属性,您可以执行相同的操作。这是我们的代码:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

然后只需使用[NoCache]装饰您的控制器。或为所有目的做到这一点,您只需将属性放在您从中继承控制器的基类的类(如果有的话)上,就像我们在这里看到的那样:

[NoCache]
public class ControllerBase : Controller, IControllerBase

如果您需要一些不可缓存的动作,也可以用此属性装饰一些动作,而不是装饰整个控制器。

或者您可以使用内置的缓存属性来防止缓存。

对于.net Framework:[OutputCache(NoStore = true, Duration = 0)]

对于.net Core:[ResponseCache(NoStore = true, Duration = 0)]

相关问题