Reacting to Hosting IServerFactory refactoring

This commit is contained in:
John Luo 2015-10-22 20:28:36 -07:00
parent c4a5d0c8b7
commit 092f689c6a
16 changed files with 261 additions and 332 deletions

View File

@ -16,25 +16,28 @@
// permissions and limitations under the License. // permissions and limitations under the License.
using System; using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts; using System.Diagnostics.Contracts;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features; using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Server.Features;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Server; using Microsoft.Net.Http.Server;
namespace Microsoft.AspNet.Server.WebListener namespace Microsoft.AspNet.Server.WebListener
{ {
using AppFunc = Func<IFeatureCollection, Task>; internal class MessagePump : IServer
internal class MessagePump : IDisposable
{ {
private static readonly int DefaultMaxAccepts = 5 * Environment.ProcessorCount; private static readonly int DefaultMaxAccepts = 5 * Environment.ProcessorCount;
private readonly Microsoft.Net.Http.Server.WebListener _listener; private readonly Microsoft.Net.Http.Server.WebListener _listener;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IHttpContextFactory _httpContextFactory;
private AppFunc _appFunc; private RequestDelegate _appFunc;
private int _maxAccepts; private int _maxAccepts;
private int _acceptorCounts; private int _acceptorCounts;
@ -43,14 +46,19 @@ namespace Microsoft.AspNet.Server.WebListener
private bool _stopping; private bool _stopping;
private int _outstandingRequests; private int _outstandingRequests;
private ManualResetEvent _shutdownSignal; private ManualResetEvent _shutdownSignal;
// TODO: private IDictionary<string, object> _capabilities; internal MessagePump(Microsoft.Net.Http.Server.WebListener listener, ILoggerFactory loggerFactory, IFeatureCollection features, IHttpContextFactory httpContextFactory)
internal MessagePump(Microsoft.Net.Http.Server.WebListener listener, ILoggerFactory loggerFactory)
{ {
if (features == null)
{
throw new ArgumentNullException(nameof(Features));
}
Contract.Assert(listener != null); Contract.Assert(listener != null);
_listener = listener; _listener = listener;
_logger = LogHelper.CreateLogger(loggerFactory, typeof(MessagePump)); _logger = LogHelper.CreateLogger(loggerFactory, typeof(MessagePump));
_httpContextFactory = httpContextFactory;
Features = features;
_processRequest = new Action<object>(ProcessRequestAsync); _processRequest = new Action<object>(ProcessRequestAsync);
_maxAccepts = DefaultMaxAccepts; _maxAccepts = DefaultMaxAccepts;
@ -80,8 +88,23 @@ namespace Microsoft.AspNet.Server.WebListener
internal bool EnableResponseCaching { get; set; } = true; internal bool EnableResponseCaching { get; set; } = true;
internal void Start(AppFunc app) public IFeatureCollection Features { get; }
public void Start(RequestDelegate app)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var addressesFeature = Features.Get<IServerAddressesFeature>();
if (addressesFeature == null)
{
throw new InvalidOperationException($"{nameof(IServerAddressesFeature)} is missing.");
}
ParseAddresses(addressesFeature.Addresses, Listener);
// Can't call Start twice // Can't call Start twice
Contract.Assert(_appFunc == null); Contract.Assert(_appFunc == null);
@ -159,11 +182,14 @@ namespace Microsoft.AspNet.Server.WebListener
SetFatalResponse(requestContext, 503); SetFatalResponse(requestContext, 503);
return; return;
} }
HttpContext httpContext = null;
try try
{ {
Interlocked.Increment(ref _outstandingRequests); Interlocked.Increment(ref _outstandingRequests);
FeatureContext featureContext = new FeatureContext(requestContext, EnableResponseCaching); FeatureContext featureContext = new FeatureContext(requestContext, EnableResponseCaching);
await _appFunc(featureContext.Features).SupressContext(); httpContext = _httpContextFactory.Create(featureContext.Features);
await _appFunc(httpContext).SupressContext();
requestContext.Dispose(); requestContext.Dispose();
} }
catch (Exception ex) catch (Exception ex)
@ -182,6 +208,10 @@ namespace Microsoft.AspNet.Server.WebListener
} }
finally finally
{ {
if (httpContext != null)
{
_httpContextFactory.Dispose(httpContext);
}
if (Interlocked.Decrement(ref _outstandingRequests) == 0 && _stopping) if (Interlocked.Decrement(ref _outstandingRequests) == 0 && _stopping)
{ {
_shutdownSignal.Set(); _shutdownSignal.Set();
@ -202,6 +232,15 @@ namespace Microsoft.AspNet.Server.WebListener
context.Dispose(); context.Dispose();
} }
private void ParseAddresses(ICollection<string> addresses, Microsoft.Net.Http.Server.WebListener listener)
{
foreach (var value in addresses)
{
listener.UrlPrefixes.Add(UrlPrefix.Create(value));
}
}
public void Dispose() public void Dispose()
{ {
_stopping = true; _stopping = true;

View File

@ -35,79 +35,44 @@
// limitations under the License. // limitations under the License.
using System; using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.AspNet.Hosting.Server; using Microsoft.AspNet.Hosting.Server;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features; using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Server.Features; using Microsoft.AspNet.Server.Features;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Server;
namespace Microsoft.AspNet.Server.WebListener namespace Microsoft.AspNet.Server.WebListener
{ {
using AppFunc = Func<IFeatureCollection, Task>;
/// <summary> /// <summary>
/// Implements the setup process for this server. /// Implements the setup process for this server.
/// </summary> /// </summary>
public class ServerFactory : IServerFactory public class ServerFactory : IServerFactory
{ {
private ILoggerFactory _loggerFactory; private ILoggerFactory _loggerFactory;
private IHttpContextFactory _httpContextFactory;
public ServerFactory(ILoggerFactory loggerFactory) public ServerFactory(ILoggerFactory loggerFactory, IHttpContextFactory httpContextFactory)
{ {
_loggerFactory = loggerFactory; _loggerFactory = loggerFactory;
_httpContextFactory = httpContextFactory;
} }
/// <summary> /// <summary>
/// Creates a configurable instance of the server. /// Creates a configurable instance of the server.
/// </summary> /// </summary>
/// <param name="properties"></param> /// <param name="configuration"></param>
/// <returns>The server. Invoke Dispose to shut down.</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposed by caller")] [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposed by caller")]
public IFeatureCollection Initialize(IConfiguration configuration) public IServer CreateServer(IConfiguration configuration)
{ {
Microsoft.Net.Http.Server.WebListener listener = new Microsoft.Net.Http.Server.WebListener(_loggerFactory); Microsoft.Net.Http.Server.WebListener listener = new Microsoft.Net.Http.Server.WebListener(_loggerFactory);
var serverFeatures = new FeatureCollection(); var serverFeatures = new FeatureCollection();
serverFeatures.Set(listener); serverFeatures.Set(listener);
serverFeatures.Set(new MessagePump(listener, _loggerFactory));
serverFeatures.Set(SplitAddresses(configuration)); serverFeatures.Set(SplitAddresses(configuration));
return serverFeatures;
}
/// <summary> return new MessagePump(listener, _loggerFactory, serverFeatures, _httpContextFactory);
/// </summary>
/// <param name="app">The per-request application entry point.</param>
/// <param name="server">The value returned </param>
/// <returns>The server. Invoke Dispose to shut down.</returns>
public IDisposable Start(IFeatureCollection serverFeatures, AppFunc app)
{
if (serverFeatures == null)
{
throw new ArgumentNullException("serverFeatures");
}
if (app == null)
{
throw new ArgumentNullException("app");
}
var messagePump = serverFeatures.Get<MessagePump>();
if (messagePump == null)
{
throw new InvalidOperationException("messagePump");
}
var addressesFeature = serverFeatures.Get<IServerAddressesFeature>();
if (addressesFeature == null)
{
throw new InvalidOperationException("IServerAddressesFeature");
}
ParseAddresses(addressesFeature.Addresses, messagePump.Listener);
messagePump.Start(app);
return messagePump;
} }
private IServerAddressesFeature SplitAddresses(IConfiguration config) private IServerAddressesFeature SplitAddresses(IConfiguration config)
@ -123,13 +88,5 @@ namespace Microsoft.AspNet.Server.WebListener
} }
return addressesFeature; return addressesFeature;
} }
private void ParseAddresses(ICollection<string> addresses, Microsoft.Net.Http.Server.WebListener listener)
{
foreach (var value in addresses)
{
listener.UrlPrefixes.Add(UrlPrefix.Create(value));
}
}
} }
} }

View File

@ -40,11 +40,11 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task AuthTypes_AllowAnonymous_NoChallenge(AuthenticationSchemes authType) public async Task AuthTypes_AllowAnonymous_NoChallenge(AuthenticationSchemes authType)
{ {
string address; string address;
using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, env => using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.False(context.User.Identity.IsAuthenticated); Assert.False(httpContext.User.Identity.IsAuthenticated);
return Task.FromResult(0); return Task.FromResult(0);
})) }))
{ {
@ -62,7 +62,7 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task AuthType_RequireAuth_ChallengesAdded(AuthenticationSchemes authType) public async Task AuthType_RequireAuth_ChallengesAdded(AuthenticationSchemes authType)
{ {
string address; string address;
using (Utilities.CreateHttpAuthServer(authType, out address, env => using (Utilities.CreateHttpAuthServer(authType, out address, httpContext =>
{ {
throw new NotImplementedException(); throw new NotImplementedException();
})) }))
@ -81,12 +81,12 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task AuthType_AllowAnonymousButSpecify401_ChallengesAdded(AuthenticationSchemes authType) public async Task AuthType_AllowAnonymousButSpecify401_ChallengesAdded(AuthenticationSchemes authType)
{ {
string address; string address;
using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, env => using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.False(context.User.Identity.IsAuthenticated); Assert.False(httpContext.User.Identity.IsAuthenticated);
context.Response.StatusCode = 401; httpContext.Response.StatusCode = 401;
return Task.FromResult(0); return Task.FromResult(0);
})) }))
{ {
@ -107,12 +107,12 @@ namespace Microsoft.AspNet.Server.WebListener
| AuthenticationSchemes.Basic | AuthenticationSchemes.Basic
| AuthenticationSchemes.AllowAnonymous, | AuthenticationSchemes.AllowAnonymous,
out address, out address,
env => httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.False(context.User.Identity.IsAuthenticated); Assert.False(httpContext.User.Identity.IsAuthenticated);
context.Response.StatusCode = 401; httpContext.Response.StatusCode = 401;
return Task.FromResult(0); return Task.FromResult(0);
})) }))
{ {
@ -132,18 +132,18 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
string address; string address;
int requestId = 0; int requestId = 0;
using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, env => using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
if (requestId == 0) if (requestId == 0)
{ {
Assert.False(context.User.Identity.IsAuthenticated); Assert.False(httpContext.User.Identity.IsAuthenticated);
context.Response.StatusCode = 401; httpContext.Response.StatusCode = 401;
} }
else if (requestId == 1) else if (requestId == 1)
{ {
Assert.True(context.User.Identity.IsAuthenticated); Assert.True(httpContext.User.Identity.IsAuthenticated);
} }
else else
{ {
@ -167,11 +167,11 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task AuthTypes_RequireAuth_Success(AuthenticationSchemes authType) public async Task AuthTypes_RequireAuth_Success(AuthenticationSchemes authType)
{ {
string address; string address;
using (Utilities.CreateHttpAuthServer(authType, out address, env => using (Utilities.CreateHttpAuthServer(authType, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.True(context.User.Identity.IsAuthenticated); Assert.True(httpContext.User.Identity.IsAuthenticated);
return Task.FromResult(0); return Task.FromResult(0);
})) }))
{ {
@ -189,10 +189,9 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task AuthTypes_GetSingleDescriptions(AuthenticationSchemes authType) public async Task AuthTypes_GetSingleDescriptions(AuthenticationSchemes authType)
{ {
string address; string address;
using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, env => using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); var resultList = httpContext.Authentication.GetAuthenticationSchemes();
var resultList = context.Authentication.GetAuthenticationSchemes();
if (authType == AuthenticationSchemes.AllowAnonymous) if (authType == AuthenticationSchemes.AllowAnonymous)
{ {
Assert.Equal(0, resultList.Count()); Assert.Equal(0, resultList.Count());
@ -223,10 +222,9 @@ namespace Microsoft.AspNet.Server.WebListener
| AuthenticationSchemes.NTLM | AuthenticationSchemes.NTLM
| /*AuthenticationSchemes.Digest | /*AuthenticationSchemes.Digest
|*/ AuthenticationSchemes.Basic; |*/ AuthenticationSchemes.Basic;
using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, env => using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); var resultList = httpContext.Authentication.GetAuthenticationSchemes();
var resultList = context.Authentication.GetAuthenticationSchemes();
Assert.Equal(3, resultList.Count()); Assert.Equal(3, resultList.Count());
return Task.FromResult(0); return Task.FromResult(0);
})) }))
@ -247,14 +245,14 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
string address; string address;
var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, async env => using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, async httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.False(context.User.Identity.IsAuthenticated); Assert.False(httpContext.User.Identity.IsAuthenticated);
foreach (var scheme in authTypeList) foreach (var scheme in authTypeList)
{ {
var authResults = await context.Authentication.AuthenticateAsync(scheme); var authResults = await httpContext.Authentication.AuthenticateAsync(scheme);
Assert.Null(authResults); Assert.Null(authResults);
} }
})) }))
@ -275,15 +273,15 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
string address; string address;
var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
using (Utilities.CreateHttpAuthServer(authType, out address, async env => using (Utilities.CreateHttpAuthServer(authType, out address, async httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.True(context.User.Identity.IsAuthenticated); Assert.True(httpContext.User.Identity.IsAuthenticated);
var count = 0; var count = 0;
foreach (var scheme in authTypeList) foreach (var scheme in authTypeList)
{ {
var authResults = await context.Authentication.AuthenticateAsync(scheme); var authResults = await httpContext.Authentication.AuthenticateAsync(scheme);
if (authResults != null) if (authResults != null)
{ {
count++; count++;
@ -307,12 +305,12 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
string address; string address;
var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, env => using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.False(context.User.Identity.IsAuthenticated); Assert.False(httpContext.User.Identity.IsAuthenticated);
return context.Authentication.ChallengeAsync(); return httpContext.Authentication.ChallengeAsync();
})) }))
{ {
var response = await SendRequestAsync(address); var response = await SendRequestAsync(address);
@ -331,14 +329,14 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
string address; string address;
var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, async env => using (Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address, async httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.False(context.User.Identity.IsAuthenticated); Assert.False(httpContext.User.Identity.IsAuthenticated);
foreach (var scheme in authTypeList) foreach (var scheme in authTypeList)
{ {
await context.Authentication.ChallengeAsync(scheme); await httpContext.Authentication.ChallengeAsync(scheme);
} }
})) }))
{ {
@ -357,12 +355,12 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
string address; string address;
var authTypes = AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM | /*AuthenticationSchemes.Digest |*/ AuthenticationSchemes.Basic; var authTypes = AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM | /*AuthenticationSchemes.Digest |*/ AuthenticationSchemes.Basic;
using (Utilities.CreateHttpAuthServer(authTypes | AuthenticationSchemes.AllowAnonymous, out address, env => using (Utilities.CreateHttpAuthServer(authTypes | AuthenticationSchemes.AllowAnonymous, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.False(context.User.Identity.IsAuthenticated); Assert.False(httpContext.User.Identity.IsAuthenticated);
return context.Authentication.ChallengeAsync(authType.ToString()); return httpContext.Authentication.ChallengeAsync(authType.ToString());
})) }))
{ {
var response = await SendRequestAsync(address); var response = await SendRequestAsync(address);
@ -383,12 +381,12 @@ namespace Microsoft.AspNet.Server.WebListener
var authTypes = AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM | /*AuthenticationSchemes.Digest |*/ AuthenticationSchemes.Basic; var authTypes = AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM | /*AuthenticationSchemes.Digest |*/ AuthenticationSchemes.Basic;
authTypes = authTypes & ~authType; authTypes = authTypes & ~authType;
var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
using (Utilities.CreateHttpAuthServer(authTypes | AuthenticationSchemes.AllowAnonymous, out address, env => using (Utilities.CreateHttpAuthServer(authTypes | AuthenticationSchemes.AllowAnonymous, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.False(context.User.Identity.IsAuthenticated); Assert.False(httpContext.User.Identity.IsAuthenticated);
return Assert.ThrowsAsync<InvalidOperationException>(() => context.Authentication.ChallengeAsync(authType.ToString())); return Assert.ThrowsAsync<InvalidOperationException>(() => httpContext.Authentication.ChallengeAsync(authType.ToString()));
})) }))
{ {
var response = await SendRequestAsync(address); var response = await SendRequestAsync(address);
@ -406,12 +404,12 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
string address; string address;
var authTypes = AuthenticationSchemes.AllowAnonymous | AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM | /*AuthenticationSchemes.Digest |*/ AuthenticationSchemes.Basic; var authTypes = AuthenticationSchemes.AllowAnonymous | AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM | /*AuthenticationSchemes.Digest |*/ AuthenticationSchemes.Basic;
using (Utilities.CreateHttpAuthServer(authTypes, out address, env => using (Utilities.CreateHttpAuthServer(authTypes, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.False(context.User.Identity.IsAuthenticated); Assert.False(httpContext.User.Identity.IsAuthenticated);
return context.Authentication.ForbidAsync(authType.ToString()); return httpContext.Authentication.ForbidAsync(authType.ToString());
})) }))
{ {
var response = await SendRequestAsync(address); var response = await SendRequestAsync(address);
@ -428,12 +426,12 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task AuthTypes_ChallengeAuthenticatedAuthType_Forbidden(AuthenticationSchemes authType) public async Task AuthTypes_ChallengeAuthenticatedAuthType_Forbidden(AuthenticationSchemes authType)
{ {
string address; string address;
using (Utilities.CreateHttpAuthServer(authType, out address, env => using (Utilities.CreateHttpAuthServer(authType, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.True(context.User.Identity.IsAuthenticated); Assert.True(httpContext.User.Identity.IsAuthenticated);
return context.Authentication.ChallengeAsync(authType.ToString()); return httpContext.Authentication.ChallengeAsync(authType.ToString());
})) }))
{ {
var response = await SendRequestAsync(address, useDefaultCredentials: true); var response = await SendRequestAsync(address, useDefaultCredentials: true);
@ -451,12 +449,12 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task AuthTypes_ChallengeAuthenticatedAuthTypeWithEmptyChallenge_Forbidden(AuthenticationSchemes authType) public async Task AuthTypes_ChallengeAuthenticatedAuthTypeWithEmptyChallenge_Forbidden(AuthenticationSchemes authType)
{ {
string address; string address;
using (Utilities.CreateHttpAuthServer(authType, out address, env => using (Utilities.CreateHttpAuthServer(authType, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.True(context.User.Identity.IsAuthenticated); Assert.True(httpContext.User.Identity.IsAuthenticated);
return context.Authentication.ChallengeAsync(); return httpContext.Authentication.ChallengeAsync();
})) }))
{ {
var response = await SendRequestAsync(address, useDefaultCredentials: true); var response = await SendRequestAsync(address, useDefaultCredentials: true);
@ -474,12 +472,12 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task AuthTypes_UnathorizedAuthenticatedAuthType_Unauthorized(AuthenticationSchemes authType) public async Task AuthTypes_UnathorizedAuthenticatedAuthType_Unauthorized(AuthenticationSchemes authType)
{ {
string address; string address;
using (Utilities.CreateHttpAuthServer(authType, out address, env => using (Utilities.CreateHttpAuthServer(authType, out address, httpContext =>
{ {
var context = new DefaultHttpContext((IFeatureCollection)env); Assert.NotNull(httpContext.User);
Assert.NotNull(context.User); Assert.NotNull(httpContext.User.Identity);
Assert.True(context.User.Identity.IsAuthenticated); Assert.True(httpContext.User.Identity.IsAuthenticated);
return context.Authentication.ChallengeAsync(authType.ToString(), null, ChallengeBehavior.Unauthorized); return httpContext.Authentication.ChallengeAsync(authType.ToString(), null, ChallengeBehavior.Unauthorized);
})) }))
{ {
var response = await SendRequestAsync(address, useDefaultCredentials: true); var response = await SendRequestAsync(address, useDefaultCredentials: true);

View File

@ -34,7 +34,7 @@ namespace Microsoft.AspNet.Server.WebListener
[Fact(Skip = "TODO: Add trait filtering support so these SSL tests don't get run on teamcity or the command line."), Trait("scheme", "https")] [Fact(Skip = "TODO: Add trait filtering support so these SSL tests don't get run on teamcity or the command line."), Trait("scheme", "https")]
public async Task Https_200OK_Success() public async Task Https_200OK_Success()
{ {
using (Utilities.CreateHttpsServer(env => using (Utilities.CreateHttpsServer(httpContext =>
{ {
return Task.FromResult(0); return Task.FromResult(0);
})) }))
@ -47,9 +47,8 @@ namespace Microsoft.AspNet.Server.WebListener
[Fact(Skip = "TODO: Add trait filtering support so these SSL tests don't get run on teamcity or the command line."), Trait("scheme", "https")] [Fact(Skip = "TODO: Add trait filtering support so these SSL tests don't get run on teamcity or the command line."), Trait("scheme", "https")]
public async Task Https_SendHelloWorld_Success() public async Task Https_SendHelloWorld_Success()
{ {
using (Utilities.CreateHttpsServer(env => using (Utilities.CreateHttpsServer(httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
byte[] body = Encoding.UTF8.GetBytes("Hello World"); byte[] body = Encoding.UTF8.GetBytes("Hello World");
httpContext.Response.ContentLength = body.Length; httpContext.Response.ContentLength = body.Length;
return httpContext.Response.Body.WriteAsync(body, 0, body.Length); return httpContext.Response.Body.WriteAsync(body, 0, body.Length);
@ -63,9 +62,8 @@ namespace Microsoft.AspNet.Server.WebListener
[Fact(Skip = "TODO: Add trait filtering support so these SSL tests don't get run on teamcity or the command line."), Trait("scheme", "https")] [Fact(Skip = "TODO: Add trait filtering support so these SSL tests don't get run on teamcity or the command line."), Trait("scheme", "https")]
public async Task Https_EchoHelloWorld_Success() public async Task Https_EchoHelloWorld_Success()
{ {
using (Utilities.CreateHttpsServer(env => using (Utilities.CreateHttpsServer(httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
string input = new StreamReader(httpContext.Request.Body).ReadToEnd(); string input = new StreamReader(httpContext.Request.Body).ReadToEnd();
Assert.Equal("Hello World", input); Assert.Equal("Hello World", input);
byte[] body = Encoding.UTF8.GetBytes("Hello World"); byte[] body = Encoding.UTF8.GetBytes("Hello World");
@ -82,9 +80,8 @@ namespace Microsoft.AspNet.Server.WebListener
[Fact(Skip = "TODO: Add trait filtering support so these SSL tests don't get run on teamcity or the command line."), Trait("scheme", "https")] [Fact(Skip = "TODO: Add trait filtering support so these SSL tests don't get run on teamcity or the command line."), Trait("scheme", "https")]
public async Task Https_ClientCertNotSent_ClientCertNotPresent() public async Task Https_ClientCertNotSent_ClientCertNotPresent()
{ {
using (Utilities.CreateHttpsServer(async env => using (Utilities.CreateHttpsServer(async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var tls = httpContext.Features.Get<ITlsConnectionFeature>(); var tls = httpContext.Features.Get<ITlsConnectionFeature>();
Assert.NotNull(tls); Assert.NotNull(tls);
var cert = await tls.GetClientCertificateAsync(CancellationToken.None); var cert = await tls.GetClientCertificateAsync(CancellationToken.None);
@ -100,9 +97,8 @@ namespace Microsoft.AspNet.Server.WebListener
[Fact(Skip = "TODO: Add trait filtering support so these SSL tests don't get run on teamcity or the command line."), Trait("scheme", "https")] [Fact(Skip = "TODO: Add trait filtering support so these SSL tests don't get run on teamcity or the command line."), Trait("scheme", "https")]
public async Task Https_ClientCertRequested_ClientCertPresent() public async Task Https_ClientCertRequested_ClientCertPresent()
{ {
using (Utilities.CreateHttpsServer(async env => using (Utilities.CreateHttpsServer(async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var tls = httpContext.Features.Get<ITlsConnectionFeature>(); var tls = httpContext.Features.Get<ITlsConnectionFeature>();
Assert.NotNull(tls); Assert.NotNull(tls);
var cert = await tls.GetClientCertificateAsync(CancellationToken.None); var cert = await tls.GetClientCertificateAsync(CancellationToken.None);

View File

@ -37,9 +37,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task OpaqueUpgrade_SupportKeys_Present() public async Task OpaqueUpgrade_SupportKeys_Present()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
try try
{ {
var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>();
@ -66,9 +65,8 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
bool? upgradeThrew = null; bool? upgradeThrew = null;
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
await httpContext.Response.WriteAsync("Hello World"); await httpContext.Response.WriteAsync("Hello World");
await httpContext.Response.Body.FlushAsync(); await httpContext.Response.Body.FlushAsync();
try try
@ -98,9 +96,8 @@ namespace Microsoft.AspNet.Server.WebListener
ManualResetEvent waitHandle = new ManualResetEvent(false); ManualResetEvent waitHandle = new ManualResetEvent(false);
bool? upgraded = null; bool? upgraded = null;
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.Headers["Upgrade"] = "websocket"; // Win8.1 blocks anything but WebSockets httpContext.Response.Headers["Upgrade"] = "websocket"; // Win8.1 blocks anything but WebSockets
var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>();
Assert.NotNull(opaqueFeature); Assert.NotNull(opaqueFeature);
@ -146,9 +143,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task OpaqueUpgrade_VariousMethodsUpgradeSendAndReceive_Success(string method, string extraHeader) public async Task OpaqueUpgrade_VariousMethodsUpgradeSendAndReceive_Success(string method, string extraHeader)
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
try try
{ {
httpContext.Response.Headers["Upgrade"] = "websocket"; // Win8.1 blocks anything but WebSockets httpContext.Response.Headers["Upgrade"] = "websocket"; // Win8.1 blocks anything but WebSockets
@ -190,9 +186,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task OpaqueUpgrade_InvalidMethodUpgrade_Disconnected(string method, string extraHeader) public async Task OpaqueUpgrade_InvalidMethodUpgrade_Disconnected(string method, string extraHeader)
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
try try
{ {
var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>();

View File

@ -35,9 +35,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task RequestBody_ReadSync_Success() public async Task RequestBody_ReadSync_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
byte[] input = new byte[100]; byte[] input = new byte[100];
int read = httpContext.Request.Body.Read(input, 0, input.Length); int read = httpContext.Request.Body.Read(input, 0, input.Length);
httpContext.Response.ContentLength = read; httpContext.Response.ContentLength = read;
@ -54,9 +53,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task RequestBody_ReadAync_Success() public async Task RequestBody_ReadAync_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
byte[] input = new byte[100]; byte[] input = new byte[100];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length); int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
httpContext.Response.ContentLength = read; httpContext.Response.ContentLength = read;
@ -72,9 +70,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task RequestBody_ReadBeginEnd_Success() public async Task RequestBody_ReadBeginEnd_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
byte[] input = new byte[100]; byte[] input = new byte[100];
int read = httpContext.Request.Body.EndRead(httpContext.Request.Body.BeginRead(input, 0, input.Length, null, null)); int read = httpContext.Request.Body.EndRead(httpContext.Request.Body.BeginRead(input, 0, input.Length, null, null));
httpContext.Response.ContentLength = read; httpContext.Response.ContentLength = read;
@ -92,9 +89,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task RequestBody_InvalidBuffer_ArgumentException() public async Task RequestBody_InvalidBuffer_ArgumentException()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
byte[] input = new byte[100]; byte[] input = new byte[100];
Assert.Throws<ArgumentNullException>("buffer", () => httpContext.Request.Body.Read(null, 0, 1)); Assert.Throws<ArgumentNullException>("buffer", () => httpContext.Request.Body.Read(null, 0, 1));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => httpContext.Request.Body.Read(input, -1, 1)); Assert.Throws<ArgumentOutOfRangeException>("offset", () => httpContext.Request.Body.Read(input, -1, 1));
@ -116,9 +112,8 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
StaggardContent content = new StaggardContent(); StaggardContent content = new StaggardContent();
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
byte[] input = new byte[10]; byte[] input = new byte[10];
int read = httpContext.Request.Body.Read(input, 0, input.Length); int read = httpContext.Request.Body.Read(input, 0, input.Length);
Assert.Equal(5, read); Assert.Equal(5, read);
@ -138,9 +133,8 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
StaggardContent content = new StaggardContent(); StaggardContent content = new StaggardContent();
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
byte[] input = new byte[10]; byte[] input = new byte[10];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length); int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
Assert.Equal(5, read); Assert.Equal(5, read);
@ -158,9 +152,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task RequestBody_PostWithImidateBody_Success() public async Task RequestBody_PostWithImidateBody_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
byte[] input = new byte[11]; byte[] input = new byte[11];
int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length); int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length);
Assert.Equal(10, read); Assert.Equal(10, read);

View File

@ -33,9 +33,9 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task RequestHeaders_ClientSendsDefaultHeaders_Success() public async Task RequestHeaders_ClientSendsDefaultHeaders_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var requestHeaders = new DefaultHttpContext((IFeatureCollection)env).Request.Headers; var requestHeaders = httpContext.Request.Headers;
// NOTE: The System.Net client only sends the Connection: keep-alive header on the first connection per service-point. // NOTE: The System.Net client only sends the Connection: keep-alive header on the first connection per service-point.
// Assert.Equal(2, requestHeaders.Count); // Assert.Equal(2, requestHeaders.Count);
// Assert.Equal("Keep-Alive", requestHeaders.Get("Connection")); // Assert.Equal("Keep-Alive", requestHeaders.Get("Connection"));
@ -53,9 +53,9 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task RequestHeaders_ClientSendsCustomHeaders_Success() public async Task RequestHeaders_ClientSendsCustomHeaders_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var requestHeaders = new DefaultHttpContext((IFeatureCollection)env).Request.Headers; var requestHeaders = httpContext.Request.Headers;
Assert.Equal(4, requestHeaders.Count); Assert.Equal(4, requestHeaders.Count);
Assert.False(StringValues.IsNullOrEmpty(requestHeaders["Host"])); Assert.False(StringValues.IsNullOrEmpty(requestHeaders["Host"]));
Assert.Equal("close", requestHeaders["Connection"]); Assert.Equal("close", requestHeaders["Connection"]);

View File

@ -20,6 +20,9 @@ using System.IO;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Hosting.Builder;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features; using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Internal; using Microsoft.AspNet.Http.Internal;
using Microsoft.Net.Http.Server; using Microsoft.Net.Http.Server;
@ -27,17 +30,14 @@ using Xunit;
namespace Microsoft.AspNet.Server.WebListener namespace Microsoft.AspNet.Server.WebListener
{ {
using AppFunc = Func<object, Task>;
public class RequestTests public class RequestTests
{ {
[Fact] [Fact]
public async Task Request_SimpleGet_Success() public async Task Request_SimpleGet_Success()
{ {
string root; string root;
using (Utilities.CreateHttpServerReturnRoot("/basepath", out root, env => using (Utilities.CreateHttpServerReturnRoot("/basepath", out root, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
try try
{ {
var requestInfo = httpContext.Features.Get<IHttpRequestFeature>(); var requestInfo = httpContext.Features.Get<IHttpRequestFeature>();
@ -53,7 +53,7 @@ namespace Microsoft.AspNet.Server.WebListener
Assert.Equal("HTTP/1.1", requestInfo.Protocol); Assert.Equal("HTTP/1.1", requestInfo.Protocol);
// Server Keys // Server Keys
// TODO: Assert.NotNull(env.Get<IDictionary<string, object>>("server.Capabilities")); // TODO: Assert.NotNull(httpContext.Get<IDictionary<string, object>>("server.Capabilities"));
var connectionInfo = httpContext.Features.Get<IHttpConnectionFeature>(); var connectionInfo = httpContext.Features.Get<IHttpConnectionFeature>();
Assert.Equal("::1", connectionInfo.RemoteIpAddress.ToString()); Assert.Equal("::1", connectionInfo.RemoteIpAddress.ToString());
@ -92,9 +92,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Request_PathSplitting(string pathBase, string requestPath, string expectedPathBase, string expectedPath) public async Task Request_PathSplitting(string pathBase, string requestPath, string expectedPathBase, string expectedPath)
{ {
string root; string root;
using (Utilities.CreateHttpServerReturnRoot(pathBase, out root, env => using (Utilities.CreateHttpServerReturnRoot(pathBase, out root, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
try try
{ {
var requestInfo = httpContext.Features.Get<IHttpRequestFeature>(); var requestInfo = httpContext.Features.Get<IHttpRequestFeature>();
@ -140,9 +139,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Request_MultiplePrefixes(string requestPath, string expectedPathBase, string expectedPath) public async Task Request_MultiplePrefixes(string requestPath, string expectedPathBase, string expectedPath)
{ {
string root; string root;
using (CreateServer(out root, env => using (CreateServer(out root, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var requestInfo = httpContext.Features.Get<IHttpRequestFeature>(); var requestInfo = httpContext.Features.Get<IHttpRequestFeature>();
var requestIdentifierFeature = httpContext.Features.Get<IHttpRequestIdentifierFeature>(); var requestIdentifierFeature = httpContext.Features.Get<IHttpRequestIdentifierFeature>();
try try
@ -167,22 +165,23 @@ namespace Microsoft.AspNet.Server.WebListener
} }
} }
private IDisposable CreateServer(out string root, AppFunc app) private IServer CreateServer(out string root, RequestDelegate app)
{ {
// TODO: We're just doing this to get a dynamic port. This can be removed later when we add support for hot-adding prefixes. // TODO: We're just doing this to get a dynamic port. This can be removed later when we add support for hot-adding prefixes.
var server = Utilities.CreateHttpServerReturnRoot("/", out root, app); var dynamicServer = Utilities.CreateHttpServerReturnRoot("/", out root, app);
server.Dispose(); dynamicServer.Dispose();
var rootUri = new Uri(root); var rootUri = new Uri(root);
var factory = new ServerFactory(loggerFactory: null); var factory = new ServerFactory(loggerFactory: null, httpContextFactory: new HttpContextFactory(new HttpContextAccessor()));
var serverFeatures = factory.Initialize(configuration: null); var server = factory.CreateServer(configuration: null);
var listener = serverFeatures.Get<Microsoft.Net.Http.Server.WebListener>(); var listener = server.Features.Get<Microsoft.Net.Http.Server.WebListener>();
foreach (string path in new[] { "/", "/11", "/2/3", "/2", "/11/2" }) foreach (string path in new[] { "/", "/11", "/2/3", "/2", "/11/2" })
{ {
listener.UrlPrefixes.Add(UrlPrefix.Create(rootUri.Scheme, rootUri.Host, rootUri.Port, path)); listener.UrlPrefixes.Add(UrlPrefix.Create(rootUri.Scheme, rootUri.Host, rootUri.Port, path));
} }
return factory.Start(serverFeatures, app); server.Start(app);
return server;
} }
private async Task<string> SendRequestAsync(string uri) private async Task<string> SendRequestAsync(string uri)

View File

@ -35,9 +35,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseBody_WriteNoHeaders_BuffersAndSetsContentLength() public async Task ResponseBody_WriteNoHeaders_BuffersAndSetsContentLength()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.Body.Write(new byte[10], 0, 10); httpContext.Response.Body.Write(new byte[10], 0, 10);
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
})) }))
@ -56,9 +55,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseBody_WriteNoHeadersAndFlush_DefaultsToChunked() public async Task ResponseBody_WriteNoHeadersAndFlush_DefaultsToChunked()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.Body.Write(new byte[10], 0, 10); httpContext.Response.Body.Write(new byte[10], 0, 10);
await httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); await httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
await httpContext.Response.Body.FlushAsync(); await httpContext.Response.Body.FlushAsync();
@ -78,9 +76,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseBody_WriteChunked_ManuallyChunked() public async Task ResponseBody_WriteChunked_ManuallyChunked()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.Headers["transfeR-Encoding"] = " CHunked "; httpContext.Response.Headers["transfeR-Encoding"] = " CHunked ";
Stream stream = httpContext.Response.Body; Stream stream = httpContext.Response.Body;
var responseBytes = Encoding.ASCII.GetBytes("10\r\nManually Chunked\r\n0\r\n\r\n"); var responseBytes = Encoding.ASCII.GetBytes("10\r\nManually Chunked\r\n0\r\n\r\n");
@ -101,9 +98,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseBody_WriteContentLength_PassedThrough() public async Task ResponseBody_WriteContentLength_PassedThrough()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.Headers["Content-lenGth"] = " 30 "; httpContext.Response.Headers["Content-lenGth"] = " 30 ";
Stream stream = httpContext.Response.Body; Stream stream = httpContext.Response.Body;
stream.EndWrite(stream.BeginWrite(new byte[10], 0, 10, null, null)); stream.EndWrite(stream.BeginWrite(new byte[10], 0, 10, null, null));
@ -126,9 +122,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseBody_WriteContentLengthNoneWritten_Throws() public async Task ResponseBody_WriteContentLengthNoneWritten_Throws()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.Headers["Content-lenGth"] = " 20 "; httpContext.Response.Headers["Content-lenGth"] = " 20 ";
return Task.FromResult(0); return Task.FromResult(0);
})) }))
@ -141,9 +136,8 @@ namespace Microsoft.AspNet.Server.WebListener
public void ResponseBody_WriteContentLengthNotEnoughWritten_Throws() public void ResponseBody_WriteContentLengthNotEnoughWritten_Throws()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.Headers["Content-lenGth"] = " 20 "; httpContext.Response.Headers["Content-lenGth"] = " 20 ";
httpContext.Response.Body.Write(new byte[5], 0, 5); httpContext.Response.Body.Write(new byte[5], 0, 5);
return Task.FromResult(0); return Task.FromResult(0);
@ -157,9 +151,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseBody_WriteContentLengthTooMuchWritten_Throws() public async Task ResponseBody_WriteContentLengthTooMuchWritten_Throws()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.Headers["Content-lenGth"] = " 10 "; httpContext.Response.Headers["Content-lenGth"] = " 10 ";
httpContext.Response.Body.Write(new byte[5], 0, 5); httpContext.Response.Body.Write(new byte[5], 0, 5);
httpContext.Response.Body.Write(new byte[6], 0, 6); httpContext.Response.Body.Write(new byte[6], 0, 6);
@ -177,11 +170,10 @@ namespace Microsoft.AspNet.Server.WebListener
ManualResetEvent waitHandle = new ManualResetEvent(false); ManualResetEvent waitHandle = new ManualResetEvent(false);
bool? appThrew = null; bool? appThrew = null;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
try try
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.Headers["Content-lenGth"] = " 10 "; httpContext.Response.Headers["Content-lenGth"] = " 10 ";
httpContext.Response.Body.Write(new byte[10], 0, 10); httpContext.Response.Body.Write(new byte[10], 0, 10);
httpContext.Response.Body.Write(new byte[9], 0, 9); httpContext.Response.Body.Write(new byte[9], 0, 9);

View File

@ -17,9 +17,8 @@ namespace Microsoft.AspNet.Server.WebListener.FunctionalTests
{ {
var requestCount = 1; var requestCount = 1;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(); httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString();
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
@ -35,9 +34,8 @@ namespace Microsoft.AspNet.Server.WebListener.FunctionalTests
{ {
var requestCount = 1; var requestCount = 1;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(); httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString();
httpContext.Response.Headers["Cache-Control"] = "public"; httpContext.Response.Headers["Cache-Control"] = "public";
@ -54,9 +52,8 @@ namespace Microsoft.AspNet.Server.WebListener.FunctionalTests
{ {
var requestCount = 1; var requestCount = 1;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(); httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString();
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10"; httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
@ -73,9 +70,8 @@ namespace Microsoft.AspNet.Server.WebListener.FunctionalTests
{ {
var requestCount = 1; var requestCount = 1;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(); httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString();
httpContext.Response.Headers["Cache-Control"] = "public, s-maxage=10"; httpContext.Response.Headers["Cache-Control"] = "public, s-maxage=10";
@ -92,9 +88,8 @@ namespace Microsoft.AspNet.Server.WebListener.FunctionalTests
{ {
var requestCount = 1; var requestCount = 1;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(); httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString();
httpContext.Response.Headers["Cache-Control"] = "public, max-age=0, s-maxage=10"; httpContext.Response.Headers["Cache-Control"] = "public, max-age=0, s-maxage=10";
@ -111,9 +106,8 @@ namespace Microsoft.AspNet.Server.WebListener.FunctionalTests
{ {
var requestCount = 1; var requestCount = 1;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(); httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString();
httpContext.Response.Headers["Cache-Control"] = "public"; httpContext.Response.Headers["Cache-Control"] = "public";
@ -134,9 +128,8 @@ namespace Microsoft.AspNet.Server.WebListener.FunctionalTests
{ {
var requestCount = 1; var requestCount = 1;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(); httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString();
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10"; httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
@ -156,9 +149,8 @@ namespace Microsoft.AspNet.Server.WebListener.FunctionalTests
{ {
var requestCount = 1; var requestCount = 1;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(); httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString();
httpContext.Response.Headers["Cache-Control"] = "public"; httpContext.Response.Headers["Cache-Control"] = "public";
@ -176,9 +168,8 @@ namespace Microsoft.AspNet.Server.WebListener.FunctionalTests
{ {
var requestCount = 1; var requestCount = 1;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(); httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString();
httpContext.Response.Headers["Expires"] = (DateTime.UtcNow + TimeSpan.FromSeconds(10)).ToString("r"); httpContext.Response.Headers["Expires"] = (DateTime.UtcNow + TimeSpan.FromSeconds(10)).ToString("r");
@ -195,9 +186,8 @@ namespace Microsoft.AspNet.Server.WebListener.FunctionalTests
{ {
var requestCount = 1; var requestCount = 1;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(); httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString();
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10"; httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";

View File

@ -34,7 +34,7 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseHeaders_ServerSendsDefaultHeaders_Success() public async Task ResponseHeaders_ServerSendsDefaultHeaders_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
return Task.FromResult(0); return Task.FromResult(0);
})) }))
@ -54,9 +54,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseHeaders_ServerSendsSingleValueKnownHeaders_Success() public async Task ResponseHeaders_ServerSendsSingleValueKnownHeaders_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var responseInfo = httpContext.Features.Get<IHttpResponseFeature>(); var responseInfo = httpContext.Features.Get<IHttpResponseFeature>();
var responseHeaders = responseInfo.Headers; var responseHeaders = responseInfo.Headers;
responseHeaders["WWW-Authenticate"] = new string[] { "custom1" }; responseHeaders["WWW-Authenticate"] = new string[] { "custom1" };
@ -79,9 +78,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseHeaders_ServerSendsMultiValueKnownHeaders_Success() public async Task ResponseHeaders_ServerSendsMultiValueKnownHeaders_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var responseInfo = httpContext.Features.Get<IHttpResponseFeature>(); var responseInfo = httpContext.Features.Get<IHttpResponseFeature>();
var responseHeaders = responseInfo.Headers; var responseHeaders = responseInfo.Headers;
responseHeaders["WWW-Authenticate"] = new string[] { "custom1, and custom2", "custom3" }; responseHeaders["WWW-Authenticate"] = new string[] { "custom1, and custom2", "custom3" };
@ -104,9 +102,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseHeaders_ServerSendsCustomHeaders_Success() public async Task ResponseHeaders_ServerSendsCustomHeaders_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var responseInfo = httpContext.Features.Get<IHttpResponseFeature>(); var responseInfo = httpContext.Features.Get<IHttpResponseFeature>();
var responseHeaders = responseInfo.Headers; var responseHeaders = responseInfo.Headers;
responseHeaders["Custom-Header1"] = new string[] { "custom1, and custom2", "custom3" }; responseHeaders["Custom-Header1"] = new string[] { "custom1, and custom2", "custom3" };
@ -129,9 +126,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseHeaders_ServerSendsConnectionClose_Closed() public async Task ResponseHeaders_ServerSendsConnectionClose_Closed()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var responseInfo = httpContext.Features.Get<IHttpResponseFeature>(); var responseInfo = httpContext.Features.Get<IHttpResponseFeature>();
var responseHeaders = responseInfo.Headers; var responseHeaders = responseInfo.Headers;
responseHeaders["Connection"] = new string[] { "Close" }; responseHeaders["Connection"] = new string[] { "Close" };
@ -154,7 +150,7 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseHeaders_HTTP10Request_Gets11Close() public async Task ResponseHeaders_HTTP10Request_Gets11Close()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
return Task.FromResult(0); return Task.FromResult(0);
})) }))
@ -177,9 +173,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseHeaders_HTTP10RequestWithChunkedHeader_ManualChunking() public async Task ResponseHeaders_HTTP10RequestWithChunkedHeader_ManualChunking()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var responseInfo = httpContext.Features.Get<IHttpResponseFeature>(); var responseInfo = httpContext.Features.Get<IHttpResponseFeature>();
var responseHeaders = responseInfo.Headers; var responseHeaders = responseInfo.Headers;
responseHeaders["Transfer-Encoding"] = new string[] { "chunked" }; responseHeaders["Transfer-Encoding"] = new string[] { "chunked" };
@ -207,9 +202,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Headers_FlushSendsHeaders_Success() public async Task Headers_FlushSendsHeaders_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var responseInfo = httpContext.Features.Get<IHttpResponseFeature>(); var responseInfo = httpContext.Features.Get<IHttpResponseFeature>();
var responseHeaders = responseInfo.Headers; var responseHeaders = responseInfo.Headers;
responseHeaders.Add("Custom1", new string[] { "value1a", "value1b" }); responseHeaders.Add("Custom1", new string[] { "value1a", "value1b" });
@ -239,9 +233,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Headers_FlushAsyncSendsHeaders_Success() public async Task Headers_FlushAsyncSendsHeaders_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var responseInfo = httpContext.Features.Get<IHttpResponseFeature>(); var responseInfo = httpContext.Features.Get<IHttpResponseFeature>();
var responseHeaders = responseInfo.Headers; var responseHeaders = responseInfo.Headers;
responseHeaders.Add("Custom1", new string[] { "value1a", "value1b" }); responseHeaders.Add("Custom1", new string[] { "value1a", "value1b" });

View File

@ -47,13 +47,12 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_SupportKeys_Present() public async Task ResponseSendFile_SupportKeys_Present()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
try try
{ {
/* TODO: /* TODO:
IDictionary<string, object> capabilities = env.Get<IDictionary<string, object>>("server.Capabilities"); IDictionary<string, object> capabilities = httpContext.Get<IDictionary<string, object>>("server.Capabilities");
Assert.NotNull(capabilities); Assert.NotNull(capabilities);
Assert.Equal("1.0", capabilities.Get<string>("sendfile.Version")); Assert.Equal("1.0", capabilities.Get<string>("sendfile.Version"));
@ -91,9 +90,8 @@ namespace Microsoft.AspNet.Server.WebListener
ManualResetEvent waitHandle = new ManualResetEvent(false); ManualResetEvent waitHandle = new ManualResetEvent(false);
bool? appThrew = null; bool? appThrew = null;
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
try try
{ {
@ -124,9 +122,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_NoHeaders_DefaultsToChunked() public async Task ResponseSendFile_NoHeaders_DefaultsToChunked()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None); return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None);
})) }))
@ -144,9 +141,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_RelativeFile_Success() public async Task ResponseSendFile_RelativeFile_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
return sendFile.SendFileAsync(RelativeFilePath, 0, null, CancellationToken.None); return sendFile.SendFileAsync(RelativeFilePath, 0, null, CancellationToken.None);
})) }))
@ -164,9 +160,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_Unspecified_Chunked() public async Task ResponseSendFile_Unspecified_Chunked()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None); return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None);
})) }))
@ -184,9 +179,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_MultipleWrites_Chunked() public async Task ResponseSendFile_MultipleWrites_Chunked()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None).Wait(); sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None).Wait();
return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None); return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None);
@ -205,9 +199,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_HalfOfFile_Chunked() public async Task ResponseSendFile_HalfOfFile_Chunked()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
return sendFile.SendFileAsync(AbsoluteFilePath, 0, FileLength / 2, CancellationToken.None); return sendFile.SendFileAsync(AbsoluteFilePath, 0, FileLength / 2, CancellationToken.None);
})) }))
@ -225,9 +218,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_OffsetOutOfRange_Throws() public async Task ResponseSendFile_OffsetOutOfRange_Throws()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
return sendFile.SendFileAsync(AbsoluteFilePath, 1234567, null, CancellationToken.None); return sendFile.SendFileAsync(AbsoluteFilePath, 1234567, null, CancellationToken.None);
})) }))
@ -241,9 +233,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_CountOutOfRange_Throws() public async Task ResponseSendFile_CountOutOfRange_Throws()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
return sendFile.SendFileAsync(AbsoluteFilePath, 0, 1234567, CancellationToken.None); return sendFile.SendFileAsync(AbsoluteFilePath, 0, 1234567, CancellationToken.None);
})) }))
@ -257,9 +248,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_Count0_Chunked() public async Task ResponseSendFile_Count0_Chunked()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
return sendFile.SendFileAsync(AbsoluteFilePath, 0, 0, CancellationToken.None); return sendFile.SendFileAsync(AbsoluteFilePath, 0, 0, CancellationToken.None);
})) }))
@ -277,9 +267,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_ContentLength_PassedThrough() public async Task ResponseSendFile_ContentLength_PassedThrough()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
httpContext.Response.Headers["Content-lenGth"] = FileLength.ToString(); httpContext.Response.Headers["Content-lenGth"] = FileLength.ToString();
return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None); return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None);
@ -299,9 +288,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_ContentLengthSpecific_PassedThrough() public async Task ResponseSendFile_ContentLengthSpecific_PassedThrough()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
httpContext.Response.Headers["Content-lenGth"] = "10"; httpContext.Response.Headers["Content-lenGth"] = "10";
return sendFile.SendFileAsync(AbsoluteFilePath, 0, 10, CancellationToken.None); return sendFile.SendFileAsync(AbsoluteFilePath, 0, 10, CancellationToken.None);
@ -321,9 +309,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task ResponseSendFile_ContentLength0_PassedThrough() public async Task ResponseSendFile_ContentLength0_PassedThrough()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var sendFile = httpContext.Features.Get<IHttpSendFileFeature>(); var sendFile = httpContext.Features.Get<IHttpSendFileFeature>();
httpContext.Response.Headers["Content-lenGth"] = "0"; httpContext.Response.Headers["Content-lenGth"] = "0";
return sendFile.SendFileAsync(AbsoluteFilePath, 0, 0, CancellationToken.None); return sendFile.SendFileAsync(AbsoluteFilePath, 0, 0, CancellationToken.None);

View File

@ -31,9 +31,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Response_ServerSendsDefaultResponse_ServerProvidesStatusCodeAndReasonPhrase() public async Task Response_ServerSendsDefaultResponse_ServerProvidesStatusCodeAndReasonPhrase()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
Assert.Equal(200, httpContext.Response.StatusCode); Assert.Equal(200, httpContext.Response.StatusCode);
Assert.False(httpContext.Response.HasStarted); Assert.False(httpContext.Response.HasStarted);
return Task.FromResult(0); return Task.FromResult(0);
@ -51,11 +50,10 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Response_ServerSendsSpecificStatus_ServerProvidesReasonPhrase() public async Task Response_ServerSendsSpecificStatus_ServerProvidesReasonPhrase()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.StatusCode = 201; httpContext.Response.StatusCode = 201;
// TODO: env["owin.ResponseProtocol"] = "HTTP/1.0"; // Http.Sys ignores this value // TODO: httpContext["owin.ResponseProtocol"] = "HTTP/1.0"; // Http.Sys ignores this value
return Task.FromResult(0); return Task.FromResult(0);
})) }))
{ {
@ -71,12 +69,11 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Response_ServerSendsSpecificStatusAndReasonPhrase_PassedThrough() public async Task Response_ServerSendsSpecificStatusAndReasonPhrase_PassedThrough()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.StatusCode = 201; httpContext.Response.StatusCode = 201;
httpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "CustomReasonPhrase"; // TODO? httpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "CustomReasonPhrase"; // TODO?
// TODO: env["owin.ResponseProtocol"] = "HTTP/1.0"; // Http.Sys ignores this value // TODO: httpContext["owin.ResponseProtocol"] = "HTTP/1.0"; // Http.Sys ignores this value
return Task.FromResult(0); return Task.FromResult(0);
})) }))
{ {
@ -92,9 +89,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Response_ServerSendsCustomStatus_NoReasonPhrase() public async Task Response_ServerSendsCustomStatus_NoReasonPhrase()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.StatusCode = 901; httpContext.Response.StatusCode = 901;
return Task.FromResult(0); return Task.FromResult(0);
})) }))
@ -110,9 +106,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Response_100_Throws() public async Task Response_100_Throws()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.StatusCode = 100; httpContext.Response.StatusCode = 100;
return Task.FromResult(0); return Task.FromResult(0);
})) }))
@ -126,9 +121,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Response_0_Throws() public async Task Response_0_Throws()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.StatusCode = 0; httpContext.Response.StatusCode = 0;
return Task.FromResult(0); return Task.FromResult(0);
})) }))

View File

@ -24,6 +24,7 @@ using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Hosting.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features; using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Internal; using Microsoft.AspNet.Http.Internal;
@ -38,7 +39,7 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Server_200OK_Success() public async Task Server_200OK_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
return Task.FromResult(0); return Task.FromResult(0);
})) }))
@ -52,9 +53,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Server_SendHelloWorld_Success() public async Task Server_SendHelloWorld_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentLength = 11; httpContext.Response.ContentLength = 11;
return httpContext.Response.WriteAsync("Hello World"); return httpContext.Response.WriteAsync("Hello World");
})) }))
@ -68,9 +68,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task Server_EchoHelloWorld_Success() public async Task Server_EchoHelloWorld_Success()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
string input = new StreamReader(httpContext.Request.Body).ReadToEnd(); string input = new StreamReader(httpContext.Request.Body).ReadToEnd();
Assert.Equal("Hello World", input); Assert.Equal("Hello World", input);
httpContext.Response.ContentLength = 11; httpContext.Response.ContentLength = 11;
@ -88,10 +87,9 @@ namespace Microsoft.AspNet.Server.WebListener
Task<string> responseTask; Task<string> responseTask;
ManualResetEvent received = new ManualResetEvent(false); ManualResetEvent received = new ManualResetEvent(false);
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
received.Set(); received.Set();
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
httpContext.Response.ContentLength = 11; httpContext.Response.ContentLength = 11;
return httpContext.Response.WriteAsync("Hello World"); return httpContext.Response.WriteAsync("Hello World");
})) }))
@ -107,7 +105,7 @@ namespace Microsoft.AspNet.Server.WebListener
public void Server_AppException_ClientReset() public void Server_AppException_ClientReset()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
throw new InvalidOperationException(); throw new InvalidOperationException();
})) }))
@ -129,7 +127,7 @@ namespace Microsoft.AspNet.Server.WebListener
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
if (Interlocked.Increment(ref requestCount) == requestLimit) if (Interlocked.Increment(ref requestCount) == requestLimit)
{ {
@ -162,7 +160,7 @@ namespace Microsoft.AspNet.Server.WebListener
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
if (Interlocked.Increment(ref requestCount) == requestLimit) if (Interlocked.Increment(ref requestCount) == requestLimit)
{ {
@ -193,9 +191,8 @@ namespace Microsoft.AspNet.Server.WebListener
ManualResetEvent canceled = new ManualResetEvent(false); ManualResetEvent canceled = new ManualResetEvent(false);
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
CancellationToken ct = httpContext.RequestAborted; CancellationToken ct = httpContext.RequestAborted;
Assert.True(ct.CanBeCanceled, "CanBeCanceled"); Assert.True(ct.CanBeCanceled, "CanBeCanceled");
Assert.False(ct.IsCancellationRequested, "IsCancellationRequested"); Assert.False(ct.IsCancellationRequested, "IsCancellationRequested");
@ -228,9 +225,8 @@ namespace Microsoft.AspNet.Server.WebListener
ManualResetEvent canceled = new ManualResetEvent(false); ManualResetEvent canceled = new ManualResetEvent(false);
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
CancellationToken ct = httpContext.RequestAborted; CancellationToken ct = httpContext.RequestAborted;
Assert.True(ct.CanBeCanceled, "CanBeCanceled"); Assert.True(ct.CanBeCanceled, "CanBeCanceled");
Assert.False(ct.IsCancellationRequested, "IsCancellationRequested"); Assert.False(ct.IsCancellationRequested, "IsCancellationRequested");
@ -255,16 +251,17 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
// This is just to get a dynamic port // This is just to get a dynamic port
string address; string address;
using (Utilities.CreateHttpServer(out address, env => Task.FromResult(0))) { } using (Utilities.CreateHttpServer(out address, httpContext => Task.FromResult(0))) { }
var factory = new ServerFactory(loggerFactory: null); var factory = new ServerFactory(loggerFactory: null, httpContextFactory: new HttpContextFactory(new HttpContextAccessor()));
var serverFeatures = factory.Initialize(configuration: null); var server = factory.CreateServer(configuration: null);
var listener = serverFeatures.Get<Microsoft.Net.Http.Server.WebListener>(); var listener = server.Features.Get<Microsoft.Net.Http.Server.WebListener>();
listener.UrlPrefixes.Add(UrlPrefix.Create(address)); listener.UrlPrefixes.Add(UrlPrefix.Create(address));
listener.SetRequestQueueLimit(1001); listener.SetRequestQueueLimit(1001);
using (factory.Start(serverFeatures, env => Task.FromResult(0))) using (server)
{ {
server.Start(httpContext => Task.FromResult(0));
string response = await SendRequestAsync(address); string response = await SendRequestAsync(address);
Assert.Equal(string.Empty, response); Assert.Equal(string.Empty, response);
} }

View File

@ -16,43 +16,44 @@
// permissions and limitations under the License. // permissions and limitations under the License.
using System; using System;
using System.Threading.Tasks; using Microsoft.AspNet.Hosting.Server;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features; using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Server.Features; using Microsoft.AspNet.Server.Features;
using Microsoft.Net.Http.Server; using Microsoft.Net.Http.Server;
namespace Microsoft.AspNet.Server.WebListener namespace Microsoft.AspNet.Server.WebListener
{ {
using AppFunc = Func<object, Task>;
internal static class Utilities internal static class Utilities
{ {
private const int BasePort = 5001; private const int BasePort = 5001;
private const int MaxPort = 8000; private const int MaxPort = 8000;
private static int NextPort = BasePort; private static int NextPort = BasePort;
private static object PortLock = new object(); private static object PortLock = new object();
private static IHttpContextFactory Factory = new HttpContextFactory(new HttpContextAccessor());
internal static IDisposable CreateHttpServer(out string baseAddress, AppFunc app) internal static IServer CreateHttpServer(out string baseAddress, RequestDelegate app)
{ {
string root; string root;
return CreateDynamicHttpServer(string.Empty, AuthenticationSchemes.AllowAnonymous, out root, out baseAddress, app); return CreateDynamicHttpServer(string.Empty, AuthenticationSchemes.AllowAnonymous, out root, out baseAddress, app);
} }
internal static IDisposable CreateHttpServerReturnRoot(string path, out string root, AppFunc app) internal static IServer CreateHttpServerReturnRoot(string path, out string root, RequestDelegate app)
{ {
string baseAddress; string baseAddress;
return CreateDynamicHttpServer(path, AuthenticationSchemes.AllowAnonymous, out root, out baseAddress, app); return CreateDynamicHttpServer(path, AuthenticationSchemes.AllowAnonymous, out root, out baseAddress, app);
} }
internal static IDisposable CreateHttpAuthServer(AuthenticationSchemes authType, out string baseAddress, AppFunc app) internal static IServer CreateHttpAuthServer(AuthenticationSchemes authType, out string baseAddress, RequestDelegate app)
{ {
string root; string root;
return CreateDynamicHttpServer(string.Empty, authType, out root, out baseAddress, app); return CreateDynamicHttpServer(string.Empty, authType, out root, out baseAddress, app);
} }
internal static IDisposable CreateDynamicHttpServer(string basePath, AuthenticationSchemes authType, out string root, out string baseAddress, AppFunc app) internal static IServer CreateDynamicHttpServer(string basePath, AuthenticationSchemes authType, out string root, out string baseAddress, RequestDelegate app)
{ {
var factory = new ServerFactory(loggerFactory: null); var factory = new ServerFactory(loggerFactory: null, httpContextFactory: Factory);
lock (PortLock) lock (PortLock)
{ {
while (NextPort < MaxPort) while (NextPort < MaxPort)
@ -63,13 +64,14 @@ namespace Microsoft.AspNet.Server.WebListener
root = prefix.Scheme + "://" + prefix.Host + ":" + prefix.Port; root = prefix.Scheme + "://" + prefix.Host + ":" + prefix.Port;
baseAddress = prefix.ToString(); baseAddress = prefix.ToString();
var serverFeatures = factory.Initialize(configuration: null); var server = factory.CreateServer(configuration: null);
var listener = serverFeatures.Get<Microsoft.Net.Http.Server.WebListener>(); var listener = server.Features.Get<Microsoft.Net.Http.Server.WebListener>();
listener.UrlPrefixes.Add(prefix); listener.UrlPrefixes.Add(prefix);
listener.AuthenticationManager.AuthenticationSchemes = authType; listener.AuthenticationManager.AuthenticationSchemes = authType;
try try
{ {
return factory.Start(serverFeatures, app); server.Start(app);
return server;
} }
catch (WebListenerException) catch (WebListenerException)
{ {
@ -80,17 +82,18 @@ namespace Microsoft.AspNet.Server.WebListener
throw new Exception("Failed to locate a free port."); throw new Exception("Failed to locate a free port.");
} }
internal static IDisposable CreateHttpsServer(AppFunc app) internal static IServer CreateHttpsServer(RequestDelegate app)
{ {
return CreateServer("https", "localhost", 9090, string.Empty, app); return CreateServer("https", "localhost", 9090, string.Empty, app);
} }
internal static IDisposable CreateServer(string scheme, string host, int port, string path, AppFunc app) internal static IServer CreateServer(string scheme, string host, int port, string path, RequestDelegate app)
{ {
var factory = new ServerFactory(loggerFactory: null); var factory = new ServerFactory(loggerFactory: null, httpContextFactory: Factory);
var serverFeatures = factory.Initialize(configuration: null); var server = factory.CreateServer(configuration: null);
serverFeatures.Get<IServerAddressesFeature>().Addresses.Add(UrlPrefix.Create(scheme, host, port, path).ToString()); server.Features.Get<IServerAddressesFeature>().Addresses.Add(UrlPrefix.Create(scheme, host, port, path).ToString());
return factory.Start(serverFeatures, app); server.Start(app);
return server;
} }
} }
} }

View File

@ -35,9 +35,8 @@ namespace Microsoft.AspNet.Server.WebListener
public async Task WebSocketTests_SupportKeys_Present() public async Task WebSocketTests_SupportKeys_Present()
{ {
string address; string address;
using (Utilities.CreateHttpServer(out address, env => using (Utilities.CreateHttpServer(out address, httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
try try
{ {
var webSocketFeature = httpContext.Features.Get<IHttpWebSocketFeature>(); var webSocketFeature = httpContext.Features.Get<IHttpWebSocketFeature>();
@ -64,9 +63,8 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
bool? upgradeThrew = null; bool? upgradeThrew = null;
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
await httpContext.Response.WriteAsync("Hello World"); await httpContext.Response.WriteAsync("Hello World");
try try
{ {
@ -94,9 +92,8 @@ namespace Microsoft.AspNet.Server.WebListener
ManualResetEvent waitHandle = new ManualResetEvent(false); ManualResetEvent waitHandle = new ManualResetEvent(false);
bool? upgraded = null; bool? upgraded = null;
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var webSocketFeature = httpContext.Features.Get<IHttpWebSocketFeature>(); var webSocketFeature = httpContext.Features.Get<IHttpWebSocketFeature>();
Assert.NotNull(webSocketFeature); Assert.NotNull(webSocketFeature);
Assert.True(webSocketFeature.IsWebSocketRequest); Assert.True(webSocketFeature.IsWebSocketRequest);
@ -120,9 +117,8 @@ namespace Microsoft.AspNet.Server.WebListener
{ {
byte[] clientBuffer = new byte[] { 0x00, 0x01, 0xFF, 0x00, 0x00 }; byte[] clientBuffer = new byte[] { 0x00, 0x01, 0xFF, 0x00, 0x00 };
string address; string address;
using (Utilities.CreateHttpServer(out address, async env => using (Utilities.CreateHttpServer(out address, async httpContext =>
{ {
var httpContext = new DefaultHttpContext((IFeatureCollection)env);
var webSocketFeature = httpContext.Features.Get<IHttpWebSocketFeature>(); var webSocketFeature = httpContext.Features.Get<IHttpWebSocketFeature>();
Assert.NotNull(webSocketFeature); Assert.NotNull(webSocketFeature);
Assert.True(webSocketFeature.IsWebSocketRequest); Assert.True(webSocketFeature.IsWebSocketRequest);