Skip to content

Instantly share code, notes, and snippets.

@oliverhanappi
Last active December 31, 2020 11:18
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save oliverhanappi/3720641004576c90407eb3803490d1ce to your computer and use it in GitHub Desktop.
Save oliverhanappi/3720641004576c90407eb3803490d1ce 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));
}
}
@hajirazin
Copy link

Do you have any full fledged working copy of this implementation

@leachdaniel
Copy link

leachdaniel commented Jan 14, 2018

I tried something similar and had a problem with content negotiation and getting 406 status codes. Thought I would share my fix for this as it appears it is missing.

// enumerating the env owin.ResponseHeaders causes Content-Type to default to text/html which messes up content negotiation
// set it to empty so AspNetCore can decide the final Content-Type
features.Get<IHttpResponseFeature>().Headers["Content-Type"] = "";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment