Hitting a snag here, we have an IP Witelist blocker on our API. The WebApplicationFactory when it starts has 'null' for the IPAddress, and I can't see how to set it.
I've been googling around and trying different ideas, but so far nothing has worked.
Des anyone have any ideas?
I created a solution for this problem from combining answers from Set dummy IP address in integration test with Asp.Net Core TestServer
The benefit of this solution is that you do not need to inherit from WebApplicationFactory
_factory = new WebApplicationFactory<Startup>().WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
services.AddSingleton<IStartupFilter, CustomStartupFilter>();
});
});
I used static fields and methods to make it possible to change the IPs while in test. You could also just hardcode them like in the commented out code
public class CustomStartupFilter : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return app =>
{
app.UseMiddleware<FakeRemoteIpAddressMiddleware>();
next(app);
};
}
}
public class FakeRemoteIpAddressMiddleware
{
private readonly RequestDelegate next;
private static IPAddress fakeIpAddress = IPAddress.Parse("127.168.1.32");
public static void RandomizeIp()
{
var random = new Random();
byte[] bytes = new byte[4];
random.NextBytes(bytes);
fakeIpAddress = new IPAddress(bytes);
}
public FakeRemoteIpAddressMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext httpContext)
{
httpContext.Connection.RemoteIpAddress = fakeIpAddress;
await this.next(httpContext);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With