0
我具有以下設置:第二請求返回503服務不可用
1)API測試
public class BaseApiTest
{
private static readonly Uri BaseUri = new Uri("http://localhost");
private static HttpServer _server;
internal BaseApiTest()
{
var config = new HttpConfiguration
{
IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always
};
WebApiConfig.Register(config);
_server = new HttpServer(config);
}
~BaseApiTest()
{
_server.Dispose();
}
protected static HttpResponseMessage GetHttpResponseMessageFrom(HttpMethod method, string relativeUri)
{
using (var client = new HttpMessageInvoker(_server))
{
var absoluteUri = new Uri(BaseUri, relativeUri);
var message = new HttpRequestMessage(method, absoluteUri);
var response = client.SendAsync(message, CancellationToken.None);
return response.Result;
}
}
2)類的擴展爲每個控制器我想測試的基類:
[TestClass]
public class ChemicalApiTest : BaseApiTest
{
private const string ControllerRoutePrefix = "/api/customers/316";
[TestMethod]
public void SomeTest() {
// Act
var response =
GetHttpResponseMessageFrom(HttpMethod.Get, ControllerRoutePrefix + "/suppliers");
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); // this is OK
response =
GetHttpResponseMessageFrom(HttpMethod.Get, ControllerRoutePrefix + "/suppliers");
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); // This fails with 503
}
}
所以我想http服務器只對第一個查詢響應。這是爲什麼,如何解決它,怎麼可能有我知道(沒有看到它在文檔中的任意位置)
編輯
原來,問題就來了,從實例化客戶端HttpMessageInvoker
兩次。如果我像下面的代碼片段那樣重構BasiApiTest
類,它可以正常工作。不過,我仍然對我的問題感興趣。
public class BaseApiTest
{
private static readonly Uri BaseUri = new Uri("http://localhost");
private static HttpMessageInvoker _client;
internal BaseApiTest()
{
var config = new HttpConfiguration
{
IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always
};
WebApiConfig.Register(config);
var server = new HttpServer(config);
_client = new HttpMessageInvoker(server);
}
~BaseApiTest()
{
_client.Dispose();
}
protected static HttpResponseMessage GetHttpResponseMessageFrom(HttpMethod method, string relativeUri)
{
var absoluteUri = new Uri(BaseUri, relativeUri);
var message = new HttpRequestMessage(method, absoluteUri);
var response = _client.SendAsync(message, CancellationToken.None);
return response.Result;
}
}
你能告訴我們「GetHttpResponseMessageFrom'和'BaseApiTest'的源代碼嗎? – mjwills
@mjwills都在我的文章。第一個代碼段具有「BaseApiTest」類,其方法爲「GetHttpResponseMessageFrom」 – LIvanov