运行 ASP .NET MVC 4 中的 Owin 应用程序

Run Owin app in ASP .NET MVC 4

我有一个 ASP .NET MVC 4 项目,我正在尝试将 Owin 应用程序集成到 运行 仅用于特定路径,因此所有以 owin 开头的请求-api/* 将由 Owin 管道 Microsoft.Owin.Host.SystemWeb.OwinHttpHandler 处理,其他请求由 MVC 管道处理 System.Web.Handlers.TransferRequestHandler

为了完成这个,我有以下内容:

Web.config

<appSettings>
    <add key="owin:appStartup" value="StartupServer.Startup"/>
</appSettings>   
<system.webServer>
        <handlers>
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
            <remove name="OPTIONSVerbHandler" />
            <remove name="TRACEVerbHandler" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
            <add  name="Owin" verb="*" path="owin-api/*" type="Microsoft.Owin.Host.SystemWeb.OwinHttpHandler, Microsoft.Owin.Host.SystemWeb" />
        </handlers>
</system.webServer>

启动class:

namespace StartupServer
{

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Run(context =>
            {
                return context.Response.WriteAsync("Owin API");
            });
        }
    }
}

但是 "Owin API" 现在是每个请求的输出。如何告诉 IIS 仅当 owin-api/* 中指定的路径 Web.config?

时才使用 OwinHttpHandler

app.Run() inserts into the OWIN pipeline a middleware which does not have a next middleware reference. So you probably want to replace it with app.Use().

您可以检测到 URL 并将您的逻辑基于此。例如:

app.Use(async (context, next) =>
{
    if (context.Request.Uri.AbsolutePath.StartsWith("/owin-api"))
    {
        await context.Response.WriteAsync("Owin API");
    }
    await next();
});