已弃用的Microsoft.AspNetCore.Authentication.Cookies替代方案及配置报错问题
替代方案
原Microsoft.AspNetCore.Authentication.Cookies包已被弃用,其全部功能已整合到Microsoft.AspNetCore.Authentication核心包中。ASP.NET Core 3.0及以上版本的项目默认已包含该核心包,无需额外安装;若项目未引入,直接安装此核心包即可完全替代弃用的Cookies包。
代码报错修复
移除弃用包后,CookieAuthenticationOptions相关报错通常源于缺少命名空间引用或未正确注册Cookie认证服务,可按以下方式修复:
1. 引入正确命名空间
在代码文件顶部添加命名空间引用:
using Microsoft.AspNetCore.Authentication.Cookies;
2. 调整配置逻辑
原直接通过Configure<CookieAuthenticationOptions>的配置方式,需配合Cookie认证服务的注册,更推荐在注册服务时直接配置选项:
var services = builder.Services; // 注册Cookie认证服务并配置AccessDeniedPath services.AddCookie(options => { if (string.IsNullOrEmpty(options.AccessDeniedPath)) { options.AccessDeniedPath = new PathString("/"); } });
如果你的项目结合Azure B2C的OpenID Connect(OIDC)认证使用,通常会将Cookie设为默认认证方案,完整配置示例如下:
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; var services = builder.Services; services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) // 配置Cookie认证选项 .AddCookie(options => { if (string.IsNullOrEmpty(options.AccessDeniedPath)) { options.AccessDeniedPath = new PathString("/"); } }) // 配置Azure B2C的OIDC认证参数 .AddOpenIdConnect(options => { options.Authority = "https://你的租户.b2clogin.com/tfp/你的租户.onmicrosoft.com/你的注册登录策略"; options.ClientId = "你的客户端ID"; options.ResponseType = "code"; options.SaveTokens = true; // 其他Azure B2C相关配置项... });
若你坚持保留Configure<CookieAuthenticationOptions>的写法,必须先通过services.AddCookie()完成服务注册,否则依赖注入容器无法找到该选项实例,会引发报错。
内容的提问来源于stack exchange,提问作者Sandeep Reddy
相关产品推荐
相关产品推荐

