Asp.net-Core

在與 Asp.Net Core TestServer 的集成測試中設置虛擬 IP 地址

  • March 12, 2018

我有一個 C# Asp.Net Core (1.x) 項目,實現了一個 web REST API,及其相關的集成測試項目,在任何測試之前都有一個類似於:

// ...

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

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

HttpClient client = server.CreateClient();

// ...

在測試期間,client用於向 Web API(被測系統)發送 HTTP 請求並檢索響應。

在實際測試系統中,有一些組件從每個請求中提取發送方 IP 地址,如下所示:

HttpContext httpContext = ReceiveHttpContextDuringAuthentication();

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

現在在集成測試期間,這段程式碼無法找到 IP 地址,因為RemoteIpAddress它始終為空。

有沒有辦法從測試程式碼中將其設置為某個已知值?我在 SO 上搜尋了這裡,但找不到類似的東西。助教

您可以編寫中間件來設置自定義 IP 地址,因為此屬性是可寫的:

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

然後你可以StartupStub像這樣創建類:

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

並用它來創建一個TestServer

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

引用自:https://stackoverflow.com/questions/49244283