https://github.com/NSwag/NSwag/wiki/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.

Sample project     https://github.com/RSuter/NSwag/tree/master/src/NSwag.Sample.NetGlobalAsax

https://github.com/RSuter/NSwag/tree/master/src/    这个路径下还有一些其他的demo

Integration

1. Install NuGet packages

Install the NuGet packages:

其中Microsoft.Owin.Host.SystemWeb依赖于另外2个

Microsoft.Owin (>= 4.0.0)

Owin (>= 1.0.0)

其中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 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:

  /// <summary>
/// https://blog.rsuter.com/nswag-tutorial-integrate-the-nswag-toolchain-into-your-asp-net-web-api-project/
/// https://github.com/RSuter/NSwag/wiki/OwinGlobalAsax
/// </summary>
/// <param name="config"></param>
public static void RegisterNSwag()
{
RouteTable.Routes.MapOwinPath("swagger", app =>
{
app.UseSwaggerUi(typeof(WebApiApplication).Assembly, settings =>
{
settings.MiddlewareBasePath = "/swagger";
});
});
}

Now, start the web project and browse to "http:/localhost:port/swagger" and the Swagger UI should be loaded.

添加之后遇到的问题:

Server Error in '/LISA.WebApi.Chile' Application.


The method 'post' on path '/api/CodeStocks' is registered multiple times (check the DefaultUrlTemplate setting [default for Web API: 'api/{controller}/{id}'; for MVC projects: '{controller}/{action}/{id?}']).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The method 'post' on path '/api/CodeStocks' is registered multiple times (check the DefaultUrlTemplate setting [default for Web API: 'api/{controller}/{id}'; for MVC projects: '{controller}/{action}/{id?}']).

https://github.com/RSuter/NSwag/issues/664

@nkm8 See domaindrivendev/Swashbuckle#142 (comment) for some background information about the query parameters not being part of the path:

https://github.com/domaindrivendev/Swashbuckle/issues/142#issuecomment-66492163

Unfortunately this is a constraint imposed by the Swagger specification https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md.

I had some late involvement with the Swagger 2.0 working group and pushed hard to have this constraint removed but to no avail. As you pointed out, this does cause an issue for certain WebApi implementations. I'll describe the workaround below but first I want to play devil's advocate and look at it from an API perspective, agnostic of implementation frameworks or even specific language constructs.

In it's essence, the constraint really just says the following paths have to be described as one operation.

GET api/products
GET api/products?producType={productType}

Behind the scenes these may be implemented as separate C# or separate
Java methods, but in the context of describing a REST API, would you
describe them separately? Swagger 2.0 says "No ... it's one operation
with an optional productType parameter".

Technically, I believe they are two different resources (hence why I
opposed the constraint) but I do see some sense in the Swagger 2.0
approach. For example, I don't think I've ever seen any API docs broken
down this way - it's invariably just by path with additional information
about query parameters included.

Anyway, philosophy aside - breaking the Swagger 2.0 spec is not an option and so I can only provide some workarounds.

The most straight forward would be to consolidate your multiple,
"overloaded", actions with a single action with optional parameters. You
could even delegate internally to the private overloaded versions.

If a change to the implementation isn't an option - Swashbuckle 5.0 provides a config setting ResolveConflictingActions.
This takes a function of the form -
Func<<IEnumerable<ApiDescription>, ApiDescription> which
you can provide to consolidate the actions into one ApiDescription, and
therefore one Operation, at the documentation level only.

This "merge" process will get trickier if the response type and
errors codes also differ but at that point you'd have to ask questions
about the API design.

Hope this helps - let me know if it makes sense?

https://github.com/RSuter/NSwag/issues/1242

app.UseSwaggerUi3(typeof(Startup).Assembly, settings =>
{
settings.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
settings.GeneratorSettings.DefaultUrlTemplate = "{controller=Home}/{action=Index}/{locale?}";
settings.GeneratorSettings.IsAspNetCore = true;
});

最后搭建成功的效果

多个controller的效果图

NSwag在asp.net web api中的使用,基于Global.asax的更多相关文章

  1. ASP.NET Web API中的Controller

    虽然通过Visual Studio向导在ASP.NET Web API项目中创建的 Controller类型默认派生与抽象类型ApiController,但是ASP.NET Web API框架本身只要 ...

  2. 在ASP.NET Web API中使用OData

    http://www.alixixi.com/program/a/2015063094986.shtml 一.什么是ODataOData是一个开放的数据协议(Open Data Protocol)在A ...

  3. ASP.NET Web API 中的异常处理(转载)

    转载地址:ASP.NET Web API 中的异常处理

  4. 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化

    谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...

  5. Asp.Net Web API 2第十三课——ASP.NET Web API中的JSON和XML序列化

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文描述ASP.NET W ...

  6. ASP.NET WEB API 中的路由调试与执行过程跟踪

    路由调试 RouteDebugger 是调试 ASP.NET MVC 路由的一个好的工具,在ASP.NET WEB API中相应的有 WebApiRouteDebugger ,Nuget安装 Inst ...

  7. 能省则省:在ASP.NET Web API中通过HTTP Headers返回数据

    对于一些返回数据非常简单的 Web API,比如我们今天遇到的“返回指定用户的未读站内短消息数”,返回数据就是一个数字,如果通过 http response body 返回数据,显得有些奢侈.何不直接 ...

  8. ASP.NET Web API中的参数绑定总结

    ASP.NET Web API中的action参数类型可以分为简单类型和复杂类型. HttpResponseMessage Put(int id, Product item) id是int类型,是简单 ...

  9. 【ASP.NET Web API教程】5.5 ASP.NET Web API中的HTTP Cookie

    原文:[ASP.NET Web API教程]5.5 ASP.NET Web API中的HTTP Cookie 5.5 HTTP Cookies in ASP.NET Web API 5.5 ASP.N ...

随机推荐

  1. linux连接mysql命令

    连接MYSQL: 格式: mysql -h主机地址 -u用户名 -p用户密码 1.例1:连接到本机上的MYSQL 找到mysql的安装目录,一般可以直接键入命令mysql -uroot -p,回车后提 ...

  2. [Intellij idea]解决debug时中文显示方框问题

    1. 点击File -> Settings 进入Intellij的设置页面 2. 点击Appearance,选择Override defaults fonts by (not recommend ...

  3. window 计算机 开启事务

    window 操作系统如何开启事务 c#开发中使用事务调试程序的时候必须开启本地计算机的事务,如何开启呢: 1:控制面板 2:组件服务 3:本地DTC 4:设置 5:应用成功.

  4. 前端模板<script type="text/template" id="tmpl">

    前端模板, 比连接字符串好用多了, 还可以使用循环\判断等语句, 减少工作量 <script type="text/template" id="member-tmp ...

  5. 帝国CMS 7.2数据导入后的参数修正

    1.日期转时间戮,HTML文件名,目录名更改 update cms_ecms_jdba set newstime = UNIX_TIMESTAMP(submitTime),titleurl = CON ...

  6. https://help.aliyun.com/knowledge_detail/49787.html?spm=a2c4g.11186631.2.3.6f856f39tiE98P

    https://help.aliyun.com/knowledge_detail/49787.html?spm=a2c4g.11186631.2.3.6f856f39tiE98P

  7. CentOS安装Apache-2.4.25+安全配置

    注:以下所有操作均在CentOS 6.5 x86_64位系统下完成. #准备工作# 在安装Nginx之前,请确保已经使用yum安装了各基础组件,并且配置了www用户和用户组,具体见<CentOS ...

  8. Spring 框架的事务管理

    1. Spring 框架的事务管理相关的类和API PlateformTransactionManager 接口: 平台事务管理器(真正管理事务的类); TransactionDefinition 接 ...

  9. Java 之内部类

    概述 内部类修饰符 内部类的细节 局部内部类 匿名内部类及其应用 匿名内部类细节 内部类概述 将一个类定义在另一个类的里面, 里面的那个类就称为内部类(内置类, 嵌套类). class Outer { ...

  10. 剑指Offer——从尾到头打印链表

    题目描述: 输入一个链表,从尾到头打印链表每个节点的值. 分析: 方法1:利用栈的性质,先从头到尾遍历链表每个节点的值存入栈中,最后一个一个出栈顺序便是从尾到头的. 方法2:直接从头到尾遍历链表存储节 ...