C# HTTP客户端在集成测试中不重定向
我已设置集成测试:C# HTTP客户端在集成测试中不重定向,c#,asp.net-core,integration-testing,http-status-code-302,C#,Asp.net Core,Integration Testing,Http Status Code 302,我已设置集成测试: public class IntegrationTests { private readonly TestServer _server; private readonly HttpClient _client; public IntegrationTests() { _server = new TestServer(WebHost.CreateDefaultBuilder().UseEnvironment("Developme
public class IntegrationTests
{
private readonly TestServer _server;
private readonly HttpClient _client;
public IntegrationTests()
{
_server = new TestServer(WebHost.CreateDefaultBuilder().UseEnvironment("Development").UseStartup<Startup>())
{
PreserveExecutionContext = true,
};
_client = _server.CreateClient();
}
[Test]
public async Task RunARoute()
{
var response = await _client.GetAsync("/foo");
Check.That(response.IsSuccessStatusCode).IsTrue();
}
}
在测试方法中,我调用的路由重定向到另一个路由:return RedirectToAction(nameof(Bar))
。我想测试页面是否由Bar
方法正确返回,但不幸的是,HttpClient
没有重定向调用:我的测试失败,代码为302
我在互联网上读到,当试图从HTTPS路由重定向到HTTP路由时,通常会发生此问题,但是,好吧,这里不是这样,因为测试服务器创建了一个具有基本URLhttp://localhost/
,重定向URL是相对的(因此未指定协议)
如何确保客户端重定向呼叫?这是出于设计。如果你查一下 您将看到它没有启用自动重定向功能,这实际上是默认情况下使用的
HttpClientHandler
的一部分
TestServer
但是,在创建HttpClient
时,使用的自定义处理程序不会自动重定向。您需要具有对处理程序的访问权限,但由于测试服务器在内部创建客户机,因此无法访问该处理程序
因此,所描述的代码的行为符合预期
找到的HTTP响应状态代码302是执行重定向的常见方式
检查响应头以断言重定向位置头指向所需的URL,从而断言预期的行为
您还可以考虑手动调用重定向URL,以验证它将返回HTTP响应状态代码200 OK
[Test]
public async Task RunARoute_Should_Redirect() {
_server.PreserveExecutionContext = true;
var client = _server.CreateClient();
var response = await _client.GetAsync("/foo");
Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.Found); //302 Found
var redirectUrl = response.Headers.Location;
//assert expected redirect URL
//...
response = await _client.GetAsync(redirectUrl);
Check.That(response.IsSuccessStatusCode).IsTrue(); //200 OK
}
HTTP 302是重定向代码。检查响应标头以断言重定向位置是所需的URL。我已验证:标头中的重定向位置是
“/bar”
,那么代码的行为符合预期。@Nkosi这是怎么回事?从我所看到的,默认情况下,客户端遵循重定向。客户端不会自动重定向。您需要访问处理程序,但您无法访问,因为测试服务器创建了clients。不幸的是,这是一个聪明的想法,这不会在两次调用之间保留HttpContext.Session
。可能是因为还需要启用cookie才能保留会话data@Boiethios考虑设置<代码> FieldExcRealEngult</C> > TraceI已经用当前配置更新了我的代码
public HttpMessageHandler CreateHandler()
{
var pathBase = BaseAddress == null ? PathString.Empty : PathString.FromUriComponent(BaseAddress);
return new ClientHandler(pathBase, Application) { AllowSynchronousIO = AllowSynchronousIO, PreserveExecutionContext = PreserveExecutionContext };
}
public HttpClient CreateClient()
{
return new HttpClient(CreateHandler()) { BaseAddress = BaseAddress };
}
[Test]
public async Task RunARoute_Should_Redirect() {
_server.PreserveExecutionContext = true;
var client = _server.CreateClient();
var response = await _client.GetAsync("/foo");
Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.Found); //302 Found
var redirectUrl = response.Headers.Location;
//assert expected redirect URL
//...
response = await _client.GetAsync(redirectUrl);
Check.That(response.IsSuccessStatusCode).IsTrue(); //200 OK
}