我遇到了一点问题。我是 .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
,而是使用 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
属性就足够了。
关于.net - .net core mvc 中 session 超时时如何重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49910612/