是否可以将 Furl.Http 与 OWIN TestServer 一起使用?

Is it possible to use Furl.Http with the OWIN TestServer?

我正在使用 OWIN TestServer,它为我提供了一个 HttpClient 来执行对测试服务器的内存调用。我想知道是否有一种方法可以将现有的 HttpClient 传递给 Flurl 使用。

更新: 下面的大部分信息在 Flurl.Http 2.x 中不再相关。具体来说,Flurl 的大部分功能都包含在新的 FlurlClient 对象(包装 HttpClient)中,而不是在自定义消息处理程序中,因此如果您提供不同的 HttpClient.此外,从 Flurl.Http 2.3.1 开始,您不再需要自定义工厂来执行此操作。就这么简单:

var flurlClient = new FlurlClient(httpClient);

Flurl 提供了一个 IHttpClientFactory 界面,允许您自定义 HttpClient 构造。然而,Flurl 的大部分功能是由自定义 HttpMessageHandler 提供的,它在构造时添加到 HttpClient。您不想将其热交换为已经实例化的 HttpClient,否则您将面临破坏 Flurl 的风险。

幸运的是,OWIN TestServer 也是由 HttpMessageHandler 驱动的,您可以在创建 HttpClient.

时通过管道传输多个

从允许您传入 TestServer 实例的自定义工厂开始:

using Flurl.Http.Configuration;
using Microsoft.Owin.Testing;

public class OwinTestHttpClientFactory : DefaultHttpClientFactory
{
    private readonly TestServer _testServer;

    public OwinTestHttpClientFactory(TestServer server) {
        _testServer = server;
    }

    public override HttpMessageHandler CreateMessageHandler() {
        // TestServer's HttpMessageHandler will be added to the end of the pipeline
        return _testServer.Handler;
    }
}

工厂可以全局注册,但由于每个测试需要一个不同的 TestServer 实例,我建议将其设置在 FlurlClient 实例上,这是一个 new capability截至 Flurl.Http 0.7。所以你的测试看起来像这样:

using (var testServer = TestServer.Create(...)) {
    using (var flurlClient = new FlurlClient()) {
        flurlClient.Settings.HttpClientFactory = new OwinTestHttpClientFactory(testServer);

        // do your tests with the FlurlClient instance. 2 ways to do that:
        url.WithClient(flurlClient).PostJsonAsync(...);
        flurlClient.WithUrl(url).PostJsonAsync(...);
    }
}