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: 
You can write middleware to set custom IP Address since this property is writable:

```cs
public class FakeRemoteIpAddressMiddleware
{
    private readonly RequestDelegate next;
    private readonly IPAddress fakeIpAddress = IPAddress.Parse("127.168.1.32");

    public FakeRemoteIpAddressMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        httpContext.Connection.RemoteIpAddress = fakeIpAddress;

        await this.next(httpContext);
    }
}

```

Then you can create `StartupStub` class like this:

```cs
public class StartupStub : Startup
{
    public StartupStub(IConfiguration configuration) : base(configuration)
    {
    }

    public override void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseMiddleware<FakeRemoteIpAddressMiddleware>();
        base.Configure(app, env);
    }
}

```

And use it to create a `TestServer`: 

```cs
new TestServer(new WebHostBuilder().UseStartup<StartupStub>());

```
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>();
        });
}

```