如何在ASP.NET 5中使用基于IAppBuilder的owin中间件?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (16)

ASP.NET 5(aspnet vnext)是基于OWIN的,就像Katana一样,但有不同的抽象。值得注意的是IAppBuilder被取代IApplicationBuilder。许多中间件库依赖IAppBuilder并且尚未更新以支持ASP.NET 5

我如何在APS.NET 5中间件中使用这个OWIN中间件。两者都是基于OWIN的,所以它应该是可能的。

Microsoft.AspNet.Builder.OwinExtensions确实提供了一种UseOwin方法,但是它基于低级的OWIN签名,所以不能用于期望的方法IAppBuilder

提问于
用户回答回答于

现在可以使用该AspNet.Hosting.Katana.Extensions

这是一个稍微不同的版本,它使用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>>();
    }));
}

请注意,引用Microsoft.Owin会使应用与dnxcore50(Core CLR)不兼容。

用户回答回答于

经常引用这个框架是可兼容的,这是Thinktecture为支持它们在ASP.NET 5上的IdentityServer3而构建的扩展方法

该方法特定于IdentityServer,不支持稍后在AspNet管道中注册的任何中间件处理的请求(它不会调用下一个组件)。

这适应该方法来解决这些缺点:

internal static class IApplicationBuilderExtensions
{
  public static void UseOwin(
    this IApplicationBuilder app,
    Action<IAppBuilder> owinConfiguration )
  {
    app.UseOwin(
      addToPipeline =>
        {
          addToPipeline(
            next =>
              {
                var builder = new AppBuilder();

                owinConfiguration( builder );

                builder.Run( ctx => next( ctx.Environment ) );

                Func<IDictionary<string, object>, Task> appFunc =
                  (Func<IDictionary<string, object>, Task>)
                  builder.Build( typeof( Func<IDictionary<string, object>, Task> ) );

                return appFunc;
              } );
        } );
  }
}

它可以使用如下:

app.UseOwin(
    owin =>
        {
            // Arbitrary IAppBuilder registrations can be placed in this block

            // For example, this extension can be provided by
            // NWebsec.Owin or Thinktecture.IdentityServer3
            owin.UseHsts();
        } );

// ASP.NET 5 components, like MVC 6, will still process the request
// (assuming the request was not handled by earlier middleware)
app.UseMvc();

扫码关注云+社区