Search code examples
c#asp.net.netowin

How to use IAppBuilder-based Owin Middleware in ASP.NET 5


ASP.NET 5 (ASP.NET vNext) is OWIN based like Katana was, but has different abstractions. Notably IAppBuilder has been replaced by IApplicationBuilder. Many middleware libraries depend on IAppBuilder and have not been updated to support ASP.NET 5

How can I use this OWIN middleware in ASP.NET 5 middleware. Both are OWIN based so it should be possible.

Microsoft.AspNet.Builder.OwinExtensions does provide a UseOwin method, but it is based on the low-level OWIN signatures so cannot be used with methods expecting IAppBuilder.


Solution

  • Edit: you can now use the AspNet.Hosting.Katana.Extensions package for that.


    Here's a slightly different version, that uses AppBuilder.DefaultApp:

    public static IApplicationBuilder UseOwinAppBuilder(this IApplicationBuilder app, Action<IAppBuilder> configuration)
    {
        if (app == null)
        {
            throw new ArgumentNullException(nameof(app));
        }
    
        if (configuration == null)
        {
            throw new ArgumentNullException(nameof(configuration));
        }
    
        return app.UseOwin(setup => setup(next =>
        {
            var builder = new AppBuilder();
            var lifetime = (IApplicationLifetime) app.ApplicationServices.GetService(typeof(IApplicationLifetime));
    
            var properties = new AppProperties(builder.Properties);
            properties.AppName = app.ApplicationServices.GetApplicationUniqueIdentifier();
            properties.OnAppDisposing = lifetime.ApplicationStopping;
            properties.DefaultApp = next;
    
            configuration(builder);
    
            return builder.Build<Func<IDictionary<string, object>, Task>>();
        }));
    }
    

    Note that referencing Microsoft.Owin makes your app incompatible with dnxcore50 (Core CLR).