我的OWIN中间件被跳过?

时间:2016-02-19 13:21:06

标签: c# owin katana

我有以下代码

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        appBuilder.Use((owinContext, next) =>
        {
            return owinContext.Response.WriteAsync("1").ContinueWith(task => next()).ContinueWith(task => owinContext.Response.WriteAsync("4"));
        });
        appBuilder.Use((owinContext, next) => owinContext.Response.WriteAsync("2").ContinueWith(task => next()) );
        appBuilder.Use((owinContext, next) => owinContext.Response.WriteAsync("3").ContinueWith(task => next()));
    }
}

当我访问输出(自托管的Web应用程序)时,我得到以下内容之一:

  • 1234
  • 1243
  • 124

ordiring并不重要,但令我困扰的是当“3”没有显示时( 124 显示没有 3

怎么会被跳过?

1 个答案:

答案 0 :(得分:1)

您的ContinueWith(task=>next())来电正在任务中包装任务。您可能希望使用Unwrap扩展方法。

基本上,这些延续在您的第一个WriteAsync方法完成后运行。然后他们正在执行next(),但是返回一个新的Task,而不是等待它完成。

类似的东西:

appBuilder.Use((owinContext, next) =>
{
    return owinContext.Response.WriteAsync("1").ContinueWith(task => next()).Unwrap()
                   .ContinueWith(task => owinContext.Response.WriteAsync("4")).Unwrap();
});
appBuilder.Use((owinContext, next) => owinContext.Response.WriteAsync("2")
                   .ContinueWith(task => next()).Unwrap() );
appBuilder.Use((owinContext, next) => owinContext.Response.WriteAsync("3")
                   .ContinueWith(task => next()).Unwrap() );

(我甚至设法错过了第一个Unwrap,而另一个ContinueWith正在创建Task<Task>

或者,我会考虑使用async lambdas,它可能会更多地清理这些代码。类似的东西:

appBuilder.Use(async (owinContext, next) =>
{
    await owinContext.Response.WriteAsync("1");
    await next();
    await owinContext.Response.WriteAsync("4");
});
appBuilder.Use(async (owinContext, next) => {
    await owinContext.Response.WriteAsync("2");
    await next();
});
appBuilder.Use(async (owinContext, next) => {
    await owinContext.Response.WriteAsync("3");
    await next();
});