Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hosting ASP.NET Core in IIS without Kestrel

Our hosting department is not willing to allow ASP.NET core hosting with Kestrel running or even installing the ASP.NET Core Server Hosting Bundle (AspNetCoreModule).

Is there any alternative to allow ASP.NET core in this situation?

Environment: Windows Server 2012 R2 with latest IIS and .NET 4.6.2.

It is a shared hosting environment and the application(s) must be running in IIS.

like image 394
DavWEB Avatar asked Dec 19 '22 09:12

DavWEB


1 Answers

You can actually run ASP.NET Core in IIS within the worker process (thus not using the ASP.NET Core Module) by using OWIN.

This is possible due to the fact that ASP.NET Core can be hosted on an OWIN server and IIS can be made an OWIN Server.

Have a look at the following OWIN middleware which shows how to run ASP.NET Core on IIS. For a more complete example, see this gist: https://gist.github.com/oliverhanappi/3720641004576c90407eb3803490d1ce.

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();
    }
}
like image 179
Oliver Hanappi Avatar answered Dec 26 '22 08:12

Oliver Hanappi