.net - .net core mvc 中 session 超时时如何重定向

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

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

我有这个操作结果。

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 core。

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

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 core,但是我如何检查我的 session 是否处于事件状态以及如果没有任何 session 则将使用重定向到主页。

最佳答案

不要使用 HttpContext.Current,而是使用 OnActionExecutingActionExecutingContext 类型参数的 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 属性就足够了。

关于.net - .net core mvc 中 session 超时时如何重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49910612/

相关文章:

c# - 动态对象属性名以数字开头

.net - 我如何从大型机程序员过渡到客户端服务器程序员?

c# - 防止多个客户端使用 cookie 重播/cookie

.net - Httpwebreqest 与 Fiddler 一起使用,否则超时

c# - Net Core Connection String Dapper visual studio 2017

c# - 在每个方法中初始化一个新的套接字是一件好事吗?

.net - .Net 是否有等效的 JavaBlackBelt?

c# - 使用 Microsoft Fakes 模拟 HttpContextBase - UserGet 属性丢失

c# - 如何为不同的子类实现接口(interface)的多个实例?

c# - 即使使用 [BindProperty(SupportsGet = true)],Razor 页面也不会在 POST 上绑定(bind)属性