Search code examples
c#asp.net-coreowinowin-middleware

How to integrate existing OwinMiddleware into a .Net Core 2.0 app pipeline?


I have a handful of existing Owin middleware classes, originally written for .Net 4.6 apps, that follow this pattern:

public class MyMiddleware : OwinMiddleware
{
    public MyMiddleware(OwinMiddleware next) : base(next)
    { }

    public override async Task Invoke(IOwinContext context)
    {
        // do stuff
        await Next.Invoke(context)
    }
}

I'm writing a new .Net Core 2.0 app that I'd like to use those middlewares in (as well as some "new style" middlewares that aren't based on Owin). I'm having trouble finding good documentation or examples of doing this, at least ones that are similar to what I have (for example, this)

The one promising thing I have found is that the Microsoft.AspNetCore.Owin package includes an extension method, UseOwin() that seems to be the path forward, but I'm unable to decipher how to use it to invoke my "legacy" middlewares above. I realize that I should use UseOwin() when configuring my IApplicationBuilder but I'm not smart enough to get the details from what I'm reading online.

What's the most straightforward way to do this?


Solution

  • It seems that the most straightforward way to do this is through the UseOwin extension method.

    I was able to get this to work:

    public class MyTestMiddleware : OwinMiddleware
    {
        public MyTestMiddleware(OwinMiddleware next) : base(next) {}
    
        public override async Task Invoke(IOwinContext context)
        {
            System.Diagnostics.Debug.WriteLine("INVOKED");
    
            await Next.Invoke(context);
        }
    }
    
    app.UseOwin(setup => setup(next =>
    {
        var owinAppBuilder = new AppBuilder();
    
        // set the DefaultApp to be next so that the ASP.NET Core pipeline runs
        owinAppBuilder.Properties["builder.DefaultApp"] = next;
    
        // add your middlewares here as Types
        owinAppBuilder.Use(typeof(MyTestMiddleware));
    
        return owinAppBuilder.Build<Func<IDictionary<string, object>, Task>>();
    }));
    

    Notice that Microsoft seems to have pushed hard against OwinMiddleware classes, as this feels very hacky.