将未经授权的用户重定向到自定义登录视图 [Asp.net Core 5]

问题描述

我在针对 IdentityAsp.net Core 5 项目中使用 .Net 5。 如您所知,当将 Controller 设为 Authorize 时,任何用户尝试访问控制器中的任何 view 时,Identity 会将他重定向到 /Identity/Account/Login 剃刀页面,所以我用视图创建了自己的登录控制器。

问题: 我想让 unauthorized 用户重定向到我的自定义 login 视图,我该怎么做?

我的尝试:ConfigureServices 类的 Startup 方法中,我添加了这段代码:

        services.AddAuthentication( CookieAuthenticationDefaults.AuthenticationScheme )
                .AddCookie( options =>
                            {
                                options.LoginPath = "/Login";

                            } );

        services.AddControllersWithViews();

但仍然无法正常工作,用户仍然重定向到 /Identity/Account/Login,我希望他们骑到我的自定义 login view

解决方法

就我而言,我用以下代码替换了旧代码:

    services.ConfigureApplicationCookie( options =>
                                         {
                                             options.LoginPath = "/Login";

                                         } );

感谢Martin Costello

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...