在集成测试所针对的目标 web 项目 Program 中通过 AddCookie 设置了 CookieAuthenticationOptions.Cookie.Domain
services.AddAuthentication(CnblogsAuthenticationDefaults.AuthenticationScheme)
.AddCookie(
options =>
{
options.Cookie.Domain = "." + Constants.DefaultDomain;
});
想在集成测试的 CustomWebApplicationFactory 中将 options.Cookie.Domain 的值改为 localhost,请问如何实现?
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
// options.Cookie.Domain = "localhost";
});
}
}
用示例代码进一步说明问题
var builder = WebApplication.CreateBuilder();
var authenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;
builder.Services
.AddAuthentication(authenticationScheme)
.AddCookie(options =>
{
options.Cookie.Domain = "q.cnblogs.com";
});
// 在这里如何通过新增的代码将 options.Cookie.Domain 修改为 localhost
using var app = builder.Build();
var options = app.Services.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>();
Console.WriteLine("Cookie.Domain:" + options.Get(authenticationScheme).Cookie.Domain);
await app.StartAsync();
对于补充问题中的示例代码(修改 Cookie.Domain 的代码放在 AddCookie 之后),可以通过下面的代码解决
builder.Services.Configure<CookieAuthenticationOptions>(
authenticationScheme,
options =>
{
options.Cookie.Domain = "localhost";
});
ASP.NET Core 支持对同一个 Options 进行多次 Configure
,依次执行这些 Configure 修改 Options 中的设置
如果将修改 Cookie.Domain 的代码放在 AddCookie 之前,可以使用 PostConfigure
builder.Services.PostConfigure<CookieAuthenticationOptions>(
authenticationScheme,
options =>
{
options.Cookie.Domain = "localhost";
});
builder.Services
.AddAuthentication(authenticationScheme)
.AddCookie(options =>
{
options.Cookie.Domain = "q.cnblogs.com";
});
集成测试中的解决方法
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
services.PostConfigureAll<CookieAuthenticationOptions>(
CookieAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.Cookie.Domain = "localhost";
});
});
}
}