在asp.net MVC 4中运行Owin应用程序

本文关键字:运行 Owin 应用程序 asp net MVC | 更新日期: 2023-09-27 18:16:06

我有一个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>

启动类:

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

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

在asp.net MVC 4中运行Owin应用程序

app.Run()在OWIN管道中插入一个没有下一个中间件引用的中间件。因此,您可能需要将其替换为app.Use()

您可以检测URL并以此为基础构建逻辑。例如:

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