[英]HttpClient with BaseAddress not working (production + integration test)?
我有一個 ASP.NET Core 5 應用程序在生產中運行在 IIS 中 + 我對該應用程序進行了集成測試。 而且我有一個問題,我不知道如何在集成測試中設置我的 HttpClient 以與“生產”服務器(在我的本地 IIS 上運行的服務)和TestServer一起工作。
這就是我實例化 HttpClient 的方式:
private static HttpClient GetHttpClient(bool isProductionServer)
{
if (isProductionServer)
{
return new HttpClient {BaseAddress = new Uri("http://localhost/myservice/")};
}
var appFactory = new WebApplicationFactory<Startup>();
var testClient = appFactory.CreateClient();
return testClient;
}
正如為什么 HttpClient BaseAddress 不起作用? , 斜杠必須出現在BaseAddress
的末尾,之后,斜杠不能出現在相對 URI 的開頭。
但似乎從WebApplicationFactory
創建的測試 HttpClient 具有相反的要求,即斜杠必須出現在相對 URI 的開頭。 由於我從同一個地方獲取相對 URI,這給我帶來了問題。 我的測試從基礎測試 class 獲取 httpClient 實例,並且測試不應該關心它們是針對 IIS 還是 TestServer 執行的。 知道如何進行這項工作嗎? 為 TestServer 創建 httpClient 時可能有一些設置?
為了進一步說明問題,請看以下兩個測試:
[Test]
public async Task TestRequestOnTestServer()
{
// works only for: "/api/v1/ping", but not for "api/v1/ping" - I get 404 response
string route = ApiRoutes.V1.Health.PingGet;
var client = GetHttpClient(false);
var response = await client.GetAsync(route);
Assert.That(response.IsSuccessStatusCode);
}
[Test]
public async Task TestRequestOnProductionServer()
{
// works only for: "api/v1/ping", but not for "/api/v1/ping" - I get 404 response
string route = ApiRoutes.V1.Health.PingGet;
var client = GetHttpClient(true);
var response = await client.GetAsync(route);
Assert.That(response.IsSuccessStatusCode);
}
也許從WebApplicationFactory
創建的 HttpClient 沒有我認為的行為。 原來問題出在 Controller class 中,它具有[Route("[controller]")]
屬性,並且其中的 Ping 方法具有[Route(ApiRoutes.V1.Health.PingGet)]
。
在 IIS 中,ping 在"/api/v1/ping"
處可用(不知道為什么),但是從 VisualStudio swagger 開始時顯示實際端點是"/Health/api/v1/ping"
(這是錯誤的)。
刪除[Route("[controller]")]
屬性解決了問題,現在兩個測試都通過了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.