Sow OBM Sow OBM - 1 month ago 22
ASP.NET (C#) Question

Run Owin app in ASP .NET MVC 4

I have an ASP .NET MVC 4 project where I am trying to integrate an Owin app to run only for a specific path, so all requests starting with owin-api/* will be handled by the Owin pipeline Microsoft.Owin.Host.SystemWeb.OwinHttpHandler and the other requests by the MVC pipeline System.Web.Handlers.TransferRequestHandler

To accomplish this, I have the following:

In the 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>


The startup class:

namespace StartupServer
{

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


However "Owin API" is now the outoput for every request. How can I tell IIS to use the OwinHttpHandler only when the path owin-api/* as specified in the Web.config?

Answer

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().

You could detect the URL and base your logic on that. For example:

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