【问题标题】:How do I redirect when sessions timeout on .net core mvc.net core mvc中的会话超时时如何重定向
【发布时间】:2018-04-18 23:46:15
【问题描述】:

我有一点问题。我是 .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 核心,但是我如何检查我的会话是否处于活动状态以及是否没有任何会话将使用重定向到主页。

【问题讨论】:

    标签: .net asp.net-mvc .net-core


    【解决方案1】:

    不要使用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 属性就足够了。

    【讨论】:

    • 这个覆盖方法去哪儿了?我尝试将它放在Startup.csProgram.cs 中,但是它给出了No override method found 的错误。
    • 控制器底部。
    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 2019-08-16
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    相关资源
    最近更新 更多