swaggerui在asp.net web api core 中的應用

Swaggerui 能夠爲咱們的webapi提供美觀的在線文檔,以下圖:web

 實現步驟:json

  • NuGet Packages  Install-Package Swashbuckle.AspNetCore
  • 在startup文件中配置swagger
                // Register the Swagger generator, defining one or more Swagger documents
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new Info
                    {
                        Version = "v1",
                        Title = "ToDo API",
                        Description = "A simple example ASP.NET Core Web API",
                        TermsOfService = "None",
                        Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "https://twitter.com/spboyer" },
                        License = new License { Name = "Use under LICX", Url = "https://example.com/license" }
                    });
    
                    //Set the comments path for the swagger json and ui.
                    var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                    var xmlPath = Path.Combine(basePath, "MyWebApiCore.xml");
                    c.IncludeXmlComments(xmlPath);
                });
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
    
                app.UseMvc();
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                });
            }
    View Code

     

  • XML Comments,點擊項目屬性=》生成=》XML文檔文件打勾,而後在你的action上添加註釋
      /// <summary>
            /// Get方法無參數
            /// </summary>
            /// <returns>string[]數組</returns>
            [HttpGet]
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
            /// <summary>
            /// 根據id獲取
            /// </summary>
            /// <param name="id"></param>
            /// <returns></returns>
            /// <remarks>
            /// Note that the id is an integer.
            /// </remarks>
            [HttpGet("{id}")]
            public string Get(int id)
            {
                return "value";
            }
    View Code

     

  • 運行項目,輸入文檔地址http://localhost:58911/swagger/

    你能夠選擇方法進行在線測試api

 參考文檔:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger數組

相關文章
相關標籤/搜索