我有一个示例的asp.net核心应用程序,其自定义的IServer接口实现如下:
namespace AspNetCoreAppWithOwinHttpListenerServer
{
public class Program
{
public static void Main(string[] args)
{
IWebHost host = new WebHostBuilder()
.UseHttpListener()
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
public class OwinHttpListenerServer : IServer
{
private IDisposable _HttpListenerServer;
public IFeatureCollection Features { get; } = new FeatureCollection();
public OwinHttpListenerServer()
{
Features.Set<IServerAddressesFeature>(new ServerAddressesFeature());
}
public void Start<TContext>(IHttpApplication<TContext> application)
{
Func<IDictionary<string, object>, Task> appFunc = async env =>
{
FeatureCollection features = new FeatureCollection(new OwinFeatureCollection(env));
TContext context = application.CreateContext(features);
try
{
await application.ProcessRequestAsync(context);
}
catch (Exception ex)
{
application.DisposeContext(context, ex);
throw;
}
application.DisposeContext(context, null);
};
appFunc = OwinWebSocketAcceptAdapter.AdaptWebSockets(appFunc);
Dictionary<string, object> props = new Dictionary<string, object>();
props["host.Addresses"] = Features
.Get<IServerAddressesFeature>()
.Addresses
.Select(add => new Uri(add))
.Select(add => new Address(add.Scheme, add.Host, add.Port.ToString(), add.LocalPath).Dictionary)
.ToList();
OwinServerFactory.Initialize(props);
_HttpListenerServer = OwinServerFactory.Create(appFunc, props);
}
public void Dispose()
{
_HttpListenerServer?.Dispose();
}
}
public static class OwinHttpListenerWebHostBuilderExtensions
{
public static IWebHostBuilder UseHttpListener(this IWebHostBuilder builder)
{
return builder.ConfigureServices(services =>
{
services.AddSingleton<IServer, OwinHttpListenerServer>();
});
}
}
}
没有IIS就可以正常工作,但在IIS或IISExpress上运行会导致VSIISExeLauncher.exe“无法侦听给定端口”。
如何让自定义服务器与IIS兼容? 提前谢谢。
GitHub存储库:https://github.com/ymoradi/AspNetCoreAppWithOwinHttpListenerServer