• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

NSwag在asp.netwebapi中的使用,基于Global.asax

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

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的效果图

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
(转)理解ASP.NET中的ViewState发布时间:2022-07-10
下一篇:
asp.net结合html使用发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap