How to configure url on Host created by WebApplicationFactory?

Viewed 173

I would like to configure the IHost object created by WebApp<TStartup> in the code below to run on https://localhost:5001. How do I do that?

Ideally I would like to read this value from launchsettings.json in the same project as the startup file. However if I have to read a config file or hard code it I'm fine with that.

public class WebApp<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
 
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseUrls("https://localhost:5001");  // does not work
        
        base.ConfigureWebHost(builder);
    }

    protected override IHost CreateHost(IHostBuilder builder)
    {
 
        builder
            .UseServiceProviderFactory(new AutofacServiceProviderFactory(containerBuilder =>
            {
 
            }));

        WebHost = builder.Build();
        WebHost.Start();
        return WebHost; //base.CreateHost(builder);
    }

    protected override IHostBuilder CreateHostBuilder()
    {
        return base.CreateHostBuilder();
    }
}

Test fixture:

[Test]
public async Task Test2()
{
    webapp = new WebApp<Startup>();                 // Startup is API server project
    HttpClient httpClient = webapp.CreateClient();
    
    string url = httpClient.BaseAddress.ToString(); 
    //line above returns http://localhost:80, desired is https://localhost:5001
   
    //...
}
1 Answers

https://stackoverflow.com/a/73721704/138284 Similar to the answer I posted above for passing in command-line arguments, you can do it like this.

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
    }
}
Related