ASP.NET MVC&Angular:当会话Cookie过期时,自定义属性/ActionFilter,希望它重

ASP.NET MVC & Angular: Custom Attribute / ActionFilter when Session Cookies expire, want it to redirect to Login page but it doesn't always work

本文关键字:自定义属性 过期 ActionFilter 希望 Cookie 会话 MVC NET amp Angular ASP      更新时间:2023-09-26

详细信息

我在Angular中使用ASP.NET MVC。如果我进行硬刷新(F5),它会很好地命中我创建的属性。。此外,当会话cookie存在时,它可以很好地访问它。但是假设用户在某个页面上,并且会话cookie在其上时过期。代码仍然会访问我的Angular代码,但一旦应该首先访问我的Controller或Attribute。。事实并非如此。因此,此时网页上什么都不起作用,也不会重定向到登录屏幕。

我在谷歌上搜索了一下这个网站,但没有找到任何有效的东西。。有什么帮助吗?

我的代码

除AccountController之外的所有控制器的属性(由于某种原因,它会导致重定向循环??)。我把这个放在我所有控制器的顶部。

[CustomFilters.VerifySession]

我的自定义属性

public class CustomFilters
{
    public class VerifySessionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var userId = filterContext.HttpContext.Session["UserId"];
            var userName = filterContext.HttpContext.Session["UserName"];
            if (userId == null || userName == null)
                filterContext.Result = new RedirectResult(string.Format("/Account/Login"));
        }
    }
}

我的登录功能

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model)
{
    ...
    Session["UserId"] = UserId;
    Session["UserName"] = sql.UserProfiles.Where(c => c.UserId == UserId).Select(x => x.UserName).FirstOrDefault();
    ...
}

Web.config

<system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="1" />  //set to 1 just for testing purposes
    </authentication>
    <sessionState timeout="1" />  //set to 1 just for testing purposes
</system.web>

没有足够的细节来弄清楚发生了什么,所以有几个想法:

首先,表单身份验证模块将在未经身份验证的请求到达过滤器或控制器之前重定向。它的工作方式是,表单模块将拦截应用程序中任何地方生成的401个未经身份验证的响应,并用302个重定向到登录页面的响应代替它们。

其次,这些重定向对ajax请求无效。你没有提到你是否在浏览器的开发工具中检查了响应,但如果你发送了一个带有过期cookie的ajax请求,浏览器将自动遵循表单模块发出的重定向,但不会真正将用户重定向到登录页面,相反,你只需在ajax请求中获得登录页面的HTML作为响应数据。

因此,在我看来,您遇到的问题是表单模块将未经验证的请求重定向到登录页面,但这对angular框架发出的ajax请求不起作用。

基本上,您需要的是一些javascript代码,以识别何时收到未经验证的响应,并将页面重定向到登录页面,而不是解析响应。我自己的解决方案(不使用angular)是简单地禁用未经身份验证请求的302重定向,然后使用javascript处理401响应:在asp.net Web Api 中处理未经身份认证请求的最佳方式