如何在没有IAppBuilder的情况下向Owin添加中间件

时间:2017-03-01 11:14:26

标签: owin katana

我目前正在构建一个包含多个OWIN中间件的库。这些中间件应按特定顺序执行。在OWIN的第一个版本中,有IAppBuilder接口。但是IAppBuilder不再是OWIN的一部分,而是Microsoft.Owin的一部分。我不想强迫我的用户依赖Microsoft.Owin。

在不使用Microsoft.Owin的情况下,将中间件添加到OWIN管道的首选方法是什么?

1 个答案:

答案 0 :(得分:0)

花了一些时间,但我想我已经明白了。

首先是Owin指定的定义:

public delegate Task AppFunc(IDictionary<string, object> environment);

public delegate AppFunc MidFunc(AppFunc next);

public delegate MidFunc MidFactory(IDictionary<string, object> startupProperties);

public delegate void BuildFunc(MidFactory midFactory);

我在这里使用delegate来避免泛滥的疯狂。

IAppBuilder转到BuildFunc

public static BuildFunc UseOwin(this IAppBuilder builder)
{
    return middleware => builder.Use(middleware(builder.Properties));
}

要使用BuildFunc构建管道,您可以在BuildFunc上创建扩展程序:

public static BuildFunc UseMyFramework(this BuildFunc buildFunc)
{
    buildFunc(startupProperties => BuildPipeline(startupProperties));

    return buildFunc;
}

最好返回BuildFunc进行链接。

构建管道只不过是将MidFunc链接在一起,并且可选地以实际AppFunc结尾:

public static MidFunc BuildPipeline(IDictionary<string, object> startupProperties)
{
    return next => LogMiddleware(AuthenticateMiddleware(MyApplication));

    // Or this if you don't supply your own AppFunc
    return next => LogMiddleware(AuthenticateMiddleware(next));
}

public static AppFunc LogMiddleware(AppFunc next)
{
    AppFunc middleware = async environment =>
    {
        // Log request

        await next(environment);
    };

    return middleware;
}

public static AppFunc AuthenticateMiddleware(AppFunc next)
{
    AppFunc middleware = async environment =>
    {
        // authenticate request

        await next(environment);
    };

    return middleware;
}

public static async Task MyApplication(IDictionary<string, object> environment)
{
    await Task.CompletedTask;
}

您仍然需要将Owin实现连接到您的框架。我使用Microsoft.Owin:

app.UseOwin().UseMyFramework()