Reputation: 1260
I am trying to start a selfhosted webapi and all seems OK. Then I add the [Authorize]
attribute to the API I'm testing, and now I have to include authentication information. So I try calling this function from inside my Startup class:
private void ConfigureAuthPipeline(IAppBuilder app)
{
var listener = (HttpListener)app.Properties[typeof(HttpListener).FullName]; //Exception happens here!!
listener.AuthenticationSchemes = AuthenticationSchemes.Ntlm;
}
The problem is it does not find a property with that name, or anything with HttpListener. here's the content of the 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]}
The test method I'm trying to run is:
[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);
}
}
}
Upvotes: 0
Views: 1441
Reputation: 1260
was missing passing the HttpClientHandler
with UseDefaultCredentials = true
Working solution:
// 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);
}
}
Upvotes: 1