繁体   English   中英

.net core mvc 上的会话超时时如何重定向

[英]How do I redirect when sessions timeout on .net core mvc

我有一点问题。 我是 .net 核心的新手。 我如何编写一个中间件来检查我当前的上下文以及会话是否超时以重定向到登录页面。

我有这个动作结果。

public async Task<IActionResult> Index()
    {
        var product = await productRepository.GetAll();
        ViewBag.Title = "List Of Products";
        return View(product);
    }

现在我想做一些看起来像这样的事情。

[SessionTimeout] // use this to make my code cleaner.
public async Task<IActionResult> Index()
    {
        var product = await productRepository.GetAll();
        ViewBag.Title = "List Of Products";
        return View(product);
    }

我发现的所有这些示例都使用 .Net,而我正在尝试使用 .Net 核心。

我创建了一个类,并使用了我在网上找到的示例,但它不起作用。

public class SessionTimeout : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;
        if (HttpContext.Current.Session["ID"] == null)
        {
            filterContext.Result = new RedirectResult("~/Home/Login");
            return;
        }
        base.OnActionExecuting(filterContext);
    }
}

我收到错误 HttpContent.Current 不存在。 现在我知道是因为使用 .Net 核心,但是我如何检查我的会话是否处于活动状态以及如果我没有任何会话将使用重定向到主页。

不要使用HttpContext.Current ,而是使用OnActionExecuting方法的ActionExecutingContext类型参数的HttpContext属性。

public override void OnActionExecuting(ActionExecutingContext context)
{
    if (context.HttpContext.Session == null ||
                     !context.HttpContext.Session.TryGetValue("ID", out byte[] val))
    {
        context.Result =
            new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home",
                                                                     action = "Login" }));
    }
    base.OnActionExecuting(context);
}

您不需要明确的回报。 设置Result属性就足够了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM