在 ASP Net Core 3.1 中,使用 ajax 时,过期 cookie 不会重定向到登录页面

问题描述

在我的应用程序中,当我的 cookie 过期时,我将重定向到我的帐户/登录页面。但是当我调用 ajax 方法并且 cookie 已过期时,操作返回 401 并且我没有重定向到我的帐户/登录页面...

我在控制器上添加了 [Authorize] 属性

xhr.status 参数返回 401。

示例ajax方法

 $(document).on('click','.ajax-modal',function (event) {
    var url = $(this).data('url');
    var id = $(this).attr('data-content');
    if (id != null)
        url = url + '/' + id;
    $.get(url)
        .done(
            function (data) {
               placeholderElement.html(data);
               placeholderElement.find('.modal').modal('show');
            }
        )
        .fail(
            function (xhr,httpStatusMessage,customErrorMessage) {
                selectErrorPage(xhr.status);
            }
        );
});

我的 ConfigureServices 方法

public void ConfigureServices(IServiceCollection services)
    {
        #region Session
        services.AdddistributedMemoryCache();

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(1000);
            options.Cookie.HttpOnly = true; // permet d'empecher à du code JS d'accèder aux cookies
            // Make the session cookie essential
            options.Cookie.IsEssential = true;
        });
        #endregion

        #region Cookie

        services.AddAuthentication(options =>
                {
                    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,options =>
                {
                    options.Cookie.Name = "TestCookie";
                    options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
                    options.LoginPath = "/Account/login";
                    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                    options.Cookie.SameSite = SameSiteMode.Strict;
                });

        #endregion

感谢您的帮助

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)