我正在尝试使用 WebApplicationFactory 托管我的 api 项目。我已经重写了ConfigureWebHost并在UseUrls()方法中添加了我想要的url。我将应用程序设置为托管在 http://localhost:5000 上,但无法从浏览器访问它。调用主机中端点的唯一方法是通过 WebApplicationFactory 实例中的 CreateClient() 方法创建的 httpClient。
public class ApiHubFactory<TEntryPoint> : WebApplicationFactory<TEntryPoint> where TEntryPoint : class
{
public string HostUrl { get; set; } = "https://localhost:5001";
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseUrls("http://localhost:5000", HostUrl);
//Adding fake authentication scheme to bypass JWT authentication
builder.ConfigureServices(services =>
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = TestAuthHandler.AuthenticationScheme;
options.DefaultScheme = TestAuthHandler.AuthenticationScheme;
options.DefaultChallengeScheme = TestAuthHandler.AuthenticationScheme;
})
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.AuthenticationScheme, options => { });
});
}
}
我试图找出主机开始在 httpclient 中查找的 url。尽管我将其设置为 http://localhost:5000,但它是 127.0.0.1:80,这也无法从浏览器访问。
我也尝试过使用设置,答案来自如何在WebApplicationFactory创建的主机上配置url?
public class CustomWebApplicationFactory<TStartup>
: WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
// Notice there is no `--` prefix in "urls"
builder.UseSetting("urls", "http://localhost:1234");
// other stuff as usual
}
}
问题是
WebApplicationFactory
在内存中创建了整个应用程序。只能从工厂创建的 HttpCLient
访问。没有其他方法可以访问您的 API。如果这是您真正需要的,那么您可以创建一个常规的 WebHost,就像您在程序文件中所做的那样,在 Kestrel 中运行 API。
ublic sealed class ApiTestHost: IDisposable
{
public const string HostUrl = "http://localhost:54318";
private readonly IWebHost host;
public ApiTestHost()
{
host = WebHost.CreateDefaultBuilder()
.UseEnvironment("Development")
.UseStartup<Startup>()
.UseKestrel()
.UseUrls(HostUrl )
.Build();
host.Start();
}
public void Dispose()
{
host?.Dispose();
}
}
然后你可以在每个测试中创建一个
ApiTestHost
的实例,但最好使用像 IClassFixture
这样的东西