Question: I have a C# Asp.Net Core (1.x) project, implementing a web REST API, and its related integration test project, where before any test there's a setup similar to:

```cs
// ...

IWebHostBuilder webHostBuilder = GetWebHostBuilderSimilarToRealOne()
    .UseStartup<MyTestStartup>();

TestServer server = new TestServer(webHostBuilder);
server.BaseAddress = new Uri("http://localhost:5000");

HttpClient client = server.CreateClient();

// ...

```

During tests, the `client` is used to send HTTP requests to web API (the system under test) and retrieve responses.

Within actual system under test there's some component extracting sender IP address from each request, as in:

```cs
HttpContext httpContext = ReceiveHttpContextDuringAuthentication();

// edge cases omitted for brevity
string remoteIpAddress = httpContext?.Connection?.RemoteIpAddress?.ToString()

```

Now during integration tests this bit of code fails to find an IP address, as `RemoteIpAddress` is always null.

Is there a way to set that to some known value from within test code? I searched here on SO but could not find anything similar. TA

Answer: 
Using WebHost.CreateDefaultBuilder can mess up with your app configuration.

And there's no need to change Product code just to accommodate for testing, unless absolutely necessary.

The simplest way to add your own middleware, without overriding Startup class methods, is to add the middleware through a `IStartupFilter‍` as suggested by Elliott's answer.

But instead of using `WebHost.CreateDefaultBuilder`, just use 

```
base.CreateWebHostBuilder().ConfigureServices...

    public class CustomWAF : WebApplicationFactory<Startup>
    {
        protected override IWebHostBuilder CreateWebHostBuilder()
        {
            return base.CreateWebHostBuilder().ConfigureServices(services =>
            {
                services.AddSingleton<IStartupFilter, CustomStartupFilter>();
            });
        }
    }

```
I used [Elliott's answer](https://stackoverflow.com/a/54943385/798781) within an ASP.NET Core 2.2 project. However, updating to ASP.NET 5.0, I had to replace the override of `CreateWebHostBuilder` with the below override of `CreateHostBuilder`:

```cs
protected override IHostBuilder CreateHostBuilder()
{
    return Host
        .CreateDefaultBuilder()
        .ConfigureWebHostDefaults(builder =>
        {
            builder.UseStartup<Startup>();
        })
        .ConfigureServices(services =>
        {
            services.AddSingleton<IStartupFilter, CustomStartupFilter>();
        });
}

```