How to configure url on Host created by WebApplicationFactory?
Asked Answered
D

1

6

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
   
    //...
}
Dynel answered 11/4, 2021 at 17:1 Comment(2)
Did you find any solution to this?Jodhpurs
@JuhoRutila check this one https://mcmap.net/q/1914804/-can-39-t-configure-host-url-on-webapplicationfactoryCattima
M
3

https://mcmap.net/q/1142375/-aspnet-core-integration-test-pass-arguments-to-webapplicationfactory 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
    }
}
Malayopolynesian answered 14/9, 2022 at 21:10 Comment(1)
I will be really surprised if it works since WebApplicationFactory doesn't create an usual Host. It creates TestServer that is only accessible with its own HTTPClient that is created with WebApplicationFactoryCattima

© 2022 - 2024 — McMap. All rights reserved.