文章出處

在針對下面設置 CookieAuthenticationOptions 的擴展方法寫單元測試時遇到了問題。 

public static IServiceCollection AddCnblogsAuthentication(this IServiceCollection services, 
    IConfigurationSection redisConfiguration, 
    Action<CookieAuthenticationOptions> configureOption = null)
{
    //...
}

想通過下面的單元測試驗證對 CookieAuthenticationOptions 的設置是否生效:

public void AddCnblogsAuthenticationTest()
{
    IServiceCollection services = new ServiceCollection();
    var builder = new ConfigurationBuilder();
    builder.AddInMemoryCollection(new Dictionary<string, string>
    {
        ["redis"] = JsonConvert.SerializeObject(new CnblogsRedisOptions())
    });
    var configuration = builder.Build();

    services.AddCnblogsAuthentication(configuration.GetSection("redis"),
        option =>
        {
            option.LoginPath = "/users/signin";
        });

    var options = services.BuildServiceProvider()
        .GetRequiredService<IOptions<CookieAuthenticationOptions>>().Value;
    Assert.Equal("/users/signin", options?.LoginPath);
}

但通過依賴注入解析 IOptions<CookieAuthenticationOptions> 接口得到的 CookieAuthenticationOptions 實例的值都是默認值, AddCnblogsAuthentication() 中的設置沒生效。

后來查看 CookieAuthenticationHandler 的實現代碼才知道需要通過 IOptionsMonitor<CookieAuthenticationOptions> 接口解析,而且需要調用該接口的 Get() 方法(而不是 CurrentValue 屬性)根據指定的 AuthenticationScheme 才能獲取到所需的 CookieAuthenticationOptions 實例。

public void AddCnblogsAuthenticationTest()
{
    //...
    var options = services.BuildServiceProvider()
        .GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>()
        .Get(CookieAuthenticationDefaults.AuthenticationScheme);
    Assert.Equal("/users/signin", options?.LoginPath);
}

文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()