You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Identity认证Cookie名称获取异常及解决咨询

问题原因及解决方案

原因

你通过ConfigureApplicationCookie配置的是ASP.NET Core Identity专属的CookieAuthenticationOptions实例,它关联的是IdentityConstants.ApplicationScheme这个特定认证Scheme。而直接注入IOptions<CookieAuthenticationOptions>获取到的是未命名的默认CookieAuthenticationOptions实例,和你配置的Identity专用实例并非同一个,所以拿到的是默认值。

解决方法

方法一:通过Scheme名称获取对应配置

注入IOptionsSnapshot<CookieAuthenticationOptions>或IOptionsMonitor<CookieAuthenticationOptions>(推荐使用这两个类型,它们支持动态配置更新),然后通过Identity的默认Scheme名称获取你配置的实例:

// 控制器构造函数注入
private readonly IOptionsSnapshot<CookieAuthenticationOptions> _cookieOptions;

public YourController(IOptionsSnapshot<CookieAuthenticationOptions> cookieOptions)
{
    _cookieOptions = cookieOptions;
}

public IActionResult GetCookieName()
{
    // 获取Identity应用Cookie的配置实例
    var identityCookieConfig = _cookieOptions.Get(IdentityConstants.ApplicationScheme);
    // 获取配置的Cookie名称
    string cookieName = identityCookieConfig.Cookie.Name; // 结果为"foo"
    return Ok(cookieName);
}

补充说明

  • IOptions<T>是单例模式,不支持配置变更;IOptionsSnapshot<T>是范围服务,每次请求会重新读取配置;IOptionsMonitor<T>是单例但能监听配置变化,可根据实际场景选择。
  • 若在非控制器场景(如中间件)获取配置,同样可以用IOptionsSnapshot<CookieAuthenticationOptions>或IOptionsMonitor<CookieAuthenticationOptions>来获取指定Scheme的配置。

内容的提问来源于stack exchange,提问作者lonix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 07:34:58