【问题标题】:OWIN HttpListener not found in app.Properties在 app.Properties 中找不到 OWIN HttpListener
【发布时间】:2015-05-29 13:07:11
【问题描述】:

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

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);
        }
    }
}

【问题讨论】:

    标签: c# asp.net-web-api owin windows-authentication self-hosting


    【解决方案1】:

    缺少通过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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 2015-07-24
      • 1970-01-01
      • 2015-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多