首页 新闻 会员 周边

ASP.NET Core 中 AddAuthentication 时如何检查 scheme 是否已经注册过

0
悬赏园豆:30 [已解决问题] 解决于 2023-01-10 12:18

注册 Authentication 的代码如下

services.AddAuthentication(CnblogsAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(
        options =>
        {
            options.Cookie.Domain = "." + Constants.DefaultDomain;
        });

在 Web 项目中注册了,想在集成测试中再次注册以修改 options.Cookie.Domain 的设置

services.AddAuthentication(CnblogsAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(
        options =>
        {
            options.Cookie.Domain = "localhost"
        });

会报错

System.InvalidOperationException : Scheme already exists: Cookies

请问如何解决?

dudu的主页 dudu | 高人七级 | 园豆:31007
提问于:2023-01-10 09:26

上面的异常是在 AuthenticationOptions.cs#L42 处抛出的

dudu 1年前
< >
分享
最佳答案
0

参考 ASP.NET Core 的源码通过下面的代码解决了

var options = services.BuildServiceProvider().GetService<Options.IOptions<AuthenticationOptions>>();
if (options?.Value.SchemeMap.ContainsKey(CookieAuthenticationDefaults.AuthenticationScheme) == true)
{
    return new AuthenticationBuilder(services);
}
dudu | 高人七级 |园豆:31007 | 2023-01-10 12:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册