Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save srogovtsev/1a7d71cc16c8e1816b8b0ae3407fb195 to your computer and use it in GitHub Desktop.
Save srogovtsev/1a7d71cc16c8e1816b8b0ae3407fb195 to your computer and use it in GitHub Desktop.
Running ASP.NET Core within IIS
public class AspNetCoreOwinMiddleware<TAspNetCoreStartup> : OwinMiddleware, IServer
where TAspNetCoreStartup : class
{
private readonly IWebHost _webHost;
private Func<IOwinContext, Task> _appFunc;
IFeatureCollection IServer.Features { get; } = new FeatureCollection();
public AspNetCoreOwinMiddleware(OwinMiddleware next, IAppBuilder app)
: base(next)
{
var appProperties = new AppProperties(app.Properties);
if (appProperties.OnAppDisposing != default(CancellationToken))
appProperties.OnAppDisposing.Register(Dispose);
_webHost = new WebHostBuilder()
.ConfigureServices(s => s.AddSingleton<IServer>(this))
.UseStartup<TAspNetCoreStartup>()
.Build();
_webHost.Start();
}
void IServer.Start<TContext>(IHttpApplication<TContext> application)
{
_appFunc = async owinContext =>
{
var features = new FeatureCollection(new OwinFeatureCollection(owinContext.Environment));
var context = application.CreateContext(features);
try
{
await application.ProcessRequestAsync(context);
application.DisposeContext(context, null);
}
catch (Exception ex)
{
application.DisposeContext(context, ex);
throw;
}
};
}
public override Task Invoke(IOwinContext context)
{
if (_appFunc == null)
throw new InvalidOperationException("ASP.NET Core Web Host not started.");
return _appFunc(context);
}
public void Dispose()
{
_webHost.Dispose();
}
}
public class AspNetCoreStartup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
}
[assembly: OwinStartup(typeof(OwinStartup))]
public class OwinStartup
{
public void Configuration(IAppBuilder app)
{
// Paths in ASP.NET Core will not start with /api but with /
app.Map("/api", subApp => subApp.Use<AspNetCoreOwinMiddleware<AspNetCoreStartup>>(app));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment