-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
OwinGlobalAsax
This page explains how to use the NSwag OWIN middleware in your "Global.asax"- based web project. It is recommended to migrate your project to a completely OWIN-based project and use the OWIN middleware directly. The OWIN middlewares will be deprecated eventually and will not receive many bug fixes and new features.
1. Install NuGet packages
Install the NuGet packages:
- Microsoft.Owin.Host.SystemWeb
- NSwag.AspNet.Owin
2. Edit web.config
Then open your Web.config
and add the following app setting:
<configuration>
<appSettings>
<add key="owin:AutomaticAppStartup" value="false" />
</appSettings>
...
Now we need setup the routing of the Swagger requests. There are two alternative ways to do this:
2.a) Pipe all request to the .NET pipeline
In the system.webServer
tag, set runAllManagedModulesForAllRequests
to true
so that all requests are piped to ASP.NET:
<system.webServer>
...
<modules runAllManagedModulesForAllRequests="true" />
...
2.b) Pipe only the Swagger request to the specific middlewares
Important: The routes defined in the web.config
and the UseSwagger/UseSwaggerUi
methods must be the same:
<system.webServer>
...
<handlers>
...
<add name="NSwag" path="swagger" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
3. Edit Global.asax.cs
Now, open the Global.asax.cs
and add the following call at the beginning of the Application_Start
method:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
RouteTable.Routes.MapOwinPath("swagger", app =>
{
app.UseSwaggerUi3(typeof(WebApiApplication).Assembly, settings =>
{
settings.MiddlewareBasePath = "/swagger";
//settings.GeneratorSettings.DefaultUrlTemplate = "api/{controller}/{id}"; //this is the default one
settings.GeneratorSettings.DefaultUrlTemplate = "api/{controller}/{action}/{id}";
});
});
...
Be careful about settings.GeneratorSettings.DefaultUrlTemplate
, make sure the DefaultUrlTemplate
is the same as you configured in config.Routes.MapHttpRoute
, otherwise you will encounter exception as following:
The method 'Post' on path '/api/admin/v/product' is registered multiple times
Now, start the web project and browse to "http:/localhost:port/swagger" and the Swagger UI should be loaded.