在 app.Properties 中找不到 OWIN HttpListener

OWIN HttpListener not found in app.Properties

我正在尝试启动一个自托管的 webapi,一切似乎都正常。然后我将 [Authorize] 属性添加到我正在测试的 API 中,现在我必须包含身份验证信息。所以我尝试从我的 Startup class:

内部调用这个函数
private void ConfigureAuthPipeline(IAppBuilder app)
{
    var listener = (HttpListener)app.Properties[typeof(HttpListener).FullName]; //Exception happens here!!
    listener.AuthenticationSchemes = AuthenticationSchemes.Ntlm;
}

问题是它找不到具有该名称的 属性 或任何带有 HttpListener 的东西。这是 app.Properties:

的内容
[0]: {[builder.AddSignatureConversion, System.Action1[System.Delegate]]}
[1]: {[builder.DefaultApp, System.Func2[System.Collections.Generic.IDictionary[System.String,System.Object],System.Threading.Tasks.Task]]}
[2]: {[host.Addresses, System.Collections.Generic.List1[System.Collections.Generic.IDictionary2[System.String,System.Object]]]}
[3]: {[host.AppName, MyDLL.WebAPI.Tests.Startup, MyDLL.WebAPI.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]}
[4]: {[host.AppMode, development]}
[5]: {[host.TraceOutput, Microsoft.Owin.Hosting.Tracing.DualWriter]}
[6]: {[host.TraceSource, System.Diagnostics.TraceSource]}
[7]: {[server.LoggerFactory, System.Func2[System.String,System.Func6[System.Diagnostics.TraceEventType,System.Int32,System.Object,System.Exception,System.Func3[System.Object,System.Exception,System.String],System.Boolean]]]}
[8]: {[host.OnAppDisposing, System.Threading.CancellationToken]}

我尝试运行的测试方法是:

[Fact]
public async void TestGetValuesWithAuthorize()
{
    const string baseAddress = "http://localhost:9050/";

    // Start OWIN host 
    using (WebApp.Start<Startup>(url: baseAddress))
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseAddress);
            var response = await client.GetAsync("/api/Values");
            var result = await response.Content.ReadAsAsync<List<string>>();
            Assert.Equal(2, result.Count);
        }
    }
}

缺少通过 HttpClientHandlerUseDefaultCredentials = true

工作解决方案:

// Start OWIN host 
using (WebApp.Start<Startup>(url: baseAddress))
{
    var handler = new HttpClientHandler
    {
        UseDefaultCredentials = true
    };
    using (var client = new HttpClient(handler))
    {
        client.BaseAddress = new Uri(baseAddress);
        var response = await client.GetAsync("/api/Values");
        response.EnsureSuccessStatusCode();
        var result = await response.Content.ReadAsAsync<List<string>>();
        Assert.Equal(2, result.Count);
    }
}