Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApplicationFactory Set IP Address at startup

Tags:

c#

.net-core

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?

like image 391
toxicmog Avatar asked Oct 23 '25 18:10

toxicmog


1 Answers

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

Setup

_factory = new WebApplicationFactory<Startup>().WithWebHostBuilder(builder =>
{
    builder.ConfigureServices(services =>
    {
                
        services.AddSingleton<IStartupFilter, CustomStartupFilter>();
    });
});

Helper Classes

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);
    }
}
like image 133
Fritz Avatar answered Oct 26 '25 08:10

Fritz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!