网络核心3.1添加AddAuthentication .AddCookie不起作用

时间:2020-08-09 08:23:13

标签: .net-core-3.1

在Startup.cs文件中将函数添加为以下代码,但无法重定向,为什么?

services.AddAuthentication()

.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, 选项=> { options.ReturnUrlParameter =“ returnUrl”; options.Cookie.Name =“ AccessCookie”; options.SlidingExpiration = true; options.ExpireTimeSpan = TimeSpan.FromDays(1);

            options.Events = new CookieAuthenticationEvents
            { 
                OnRedirectToLogin = context =>
                {
                    Uri url = new Uri(System.Uri.UnescapeDataString(context.RedirectUri));
                    
                    string language;
                    if (context.Request.RouteValues["Language"] != null) 
                        language = context.Request.RouteValues["Language"].ToString(); 
                    else 
                        language = Thread.CurrentThread.CurrentCulture.Name;
                    
                     
                    options.LoginPath = new PathString($"/{language}/Account/Login"); 
                    options.LogoutPath = new PathString($"/{language}/Account/Logout");
                    options.AccessDeniedPath = new PathString($"/{language}/Account/AccessDenied");

                    if (IsAjaxRequest(context.Request))
                    {
                        
                        context.Response.Headers["Location"] = System.Uri.UnescapeDataString(context.RedirectUri);
                        context.Response.StatusCode = 401;
                        return Task.CompletedTask;
                    }
                    else
                    { 
                        string redirectUrl = $"{url.Scheme}://{url.Host}:{url.Port}/{language}{url.PathAndQuery}"; 

//像这样: http:// localhost:64842 / zh-CN / zh-CN / Account / Login?returnUrl = / zh-CN / account / register

                        context.Response.Redirect(redirectUrl);  // That is the Key Why not to  redirect 
                        return Task.CompletedTask;
                    }
                   
                }
            };
            //---
        })

0 个答案:

没有答案