zoukankan      html  css  js  c++  java
  • NSwag在asp.net web api中的使用,基于Global.asax

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

  • 相关阅读:
    ScreenToGif 使用教程
    无问西东
    php如何解决中文乱码问题?
    layer父页面调用子页面的方法
    弹层组件文档
    关于svn获取获取文件时 Unable to connect to a repository at URL"https://..."执行上下文错误:参数错误
    centos下修改文件后如何保存退出
    Linux CentOS 7的图形界面安装(GNOME、KDE等)
    CentOS7安装详解
    Could not attach to pid : "xx"最近启动Xcode运行项目都会出现这个问题,再次启动或者多启动几次,就可以正常运行工程了。
  • 原文地址:https://www.cnblogs.com/chucklu/p/10314160.html
Copyright © 2011-2022 走看看