TestServer CreateClient和HttpClientHandler - howto?

时间:2017-01-05 21:11:38

标签: .net asp.net-core dotnet-httpclient xunit

我正在使用AspNetCore TestServer并尝试连接到为NTLM身份验证配置的API服务。我要连接的服务需要访问System.Security.Claims.ClaimsPrincipal.Identity。

从我的控制台应用程序中,我可以按如下方式初始化HTTPClient,它可以正常工作

HttpClientHandler handler = new HttpClientHandler()
{
    UseDefaultCredentials = true,
    PreAuthenticate = true
};

HttpClient client = new HttpClient(handler);

但是,TestServer CreateClient方法不接受HttpClientHandler。那么如何配置使用UseDefaultCredentials?

3 个答案:

答案 0 :(得分:0)

一个选项是在HttpClientHandler上创建一个重载的构造函数并包装TestServer的HttpClientHandler。在那里,从SendAsync方法你只需要调用他的TestServer的HttpClientHandler的方法SendAsync,就像这样

if (_wrappedMessageHandler != null)
{
    var method = typeof(HttpMessageHandler).GetMethod("SendAsync", BindingFlags.Instance | BindingFlags.NonPublic);
    var result = method.Invoke(_wrappedMessageHandler, new object[] { request, cancellationToken });
    return await (Task<HttpResponseMessage>)result;
}
else
{
    var response = await base.SendAsync(request, cancellationToken);
    return response;

}

答案 1 :(得分:0)

您无法使用测试服务器执行Windows身份验证。为即将发布的版本添加了相关功能。 https://github.com/aspnet/Hosting/pull/1248。通过中间件查看链接的问题和PR以获取解决方法。

答案 2 :(得分:0)

要解决此问题,我在测试中通过中间件向用户注入了

public class FakeIdentity : IIdentity
{
    public string AuthenticationType => "fake";

    public bool IsAuthenticated => true;

    public string Name => "fake";
}

public class TestUtils
{
    public static TestServer CreateTestServer()
    {
        Startup startup = null;
        var webHostBuilder = new WebHostBuilder()
            .ConfigureServices((context, services) =>
            {
                startup = new Startup(context.Configuration);
                startup.ConfigureServices(services);
            })
            .Configure(builder =>
            {
            var services = builder.ApplicationServices;
            using (var scope = services.CreateScope())
            {
                builder.Use(async (context, next) =>
                {
                    context.User = new ClaimsPrincipal(new ClaimsIdentity(new FakeIdentity(), new List<Claim>
                    {
                                // a list of claims the application need
                            }));
                    await next();
                });
                startup.Configure(builder, services.GetRequiredService<IHostingEnvironment>());
            });

        var testServer = new TestServer(webHostBuilder);

        return testServer;
    }
}