asp.net core swagger使用及注意事项

  Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。是一款RESTFUL接口的文档在线自动生成+功能测试软件。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。

 作用:

    1. 接口的文档在线自动生成。

    2. 功能测试。

一 、swagger的创建  

1.新建asp.net core项目

2.nuget上安装Swashbuckle.AspNetCore

Swashbuckle有三个主要组件:

  • Swashbuckle.AspNetCore.Swagger:一个Swagger对象模型和中间件,用于将SwaggerDocument对象公开为JSON端点。

  • Swashbuckle.AspNetCore.SwaggerGen:一个Swagger生成器,可SwaggerDocument直接从路由,控制器和模型构建对象。它通常与Swagger端点中间件结合使用,以自动显示Swagger JSON。

    扫描二维码关注公众号,回复: 5765120 查看本文章
  • Swashbuckle.AspNetCore.SwaggerUI:Swagger UI工具的嵌入式版本。它解释了Swagger JSON,以便为描述Web API功能构建丰富,可定制的体验。它包括用于公共方法的内置测试工具。

3.在Startup的 ConfigureServices配置服务中添加中间件

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
            });
        }

4.在Startup的 Configure配置服务中启用中间件

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.InjectJavascript("");
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
        }

5.启动程序,然后键入url  swagger/index.html或者swagger

6.修改Web API项目首页重定向

在 Properties >> launchSettings.json文件中更改默认配置 >> 启用 "launchUrl": "swagger"配置

{
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:49833",
      "sslPort": 44387
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "SwaggerTest": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:49833/swagger",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

7.为控制器中每个方法添加注释启用XML注释为未记录的公共类型和成员提供调试信息     项目 >> 属性 >> 生成

修改Startup的 ConfigureServices配置服务

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
                //添加xml文件
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
        }

 8.添加控制器,启动  创建成功

二 、注意事项

1.启动后出现 No operations defined in spec! 问题

在查看/swagger/v1/swagger.json文件后发现是没有配置parh

打开后内容是:

{"swagger":"2.0","info":{"version":"v1","title":"My API"},"paths":{},"definitions":{}}

解决:该项目中未添加API控制器,注意必须是API控制器,并且需要在处理方法上添加HTTP标记

/// <summary>
        /// Delete
        /// </summary>
        /// <param name="ids">删除id列表</param>
        /// <returns>被成功删除id列表</returns>
        [HttpDelete]
        public ActionResult<IEnumerable<string>> Delete(params string[] ids)
        {
            if (ids == null)
                return NoContent();
            return ids;
        }

        /// <summary>
        /// Update
        /// </summary>
        /// <param name="id">Update id</param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Update(string id)
        {
            return Content("Update id:" + id);
        }

        /// <summary>
        /// Add
        /// </summary>
        /// <param name="param">Add ids</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add(params string[] param)
        {
            return Content(string.Join(",", param));
        }

2.启动后出现  Failed to load API definition.  错误 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace SwaggerTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DefaultController : ControllerBase
    {
        /// <summary>
        /// Delete
        /// </summary>
        /// <param name="ids">删除id列表</param>
        /// <returns>被成功删除id列表</returns>
        //[HttpDelete]
        public ActionResult<IEnumerable<string>> Delete(params string[] ids)
        {
            if (ids == null)
                return NoContent();
            return ids;
        }

        /// <summary>
        /// Update
        /// </summary>
        /// <param name="id">Update id</param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Update(string id)
        {
            return Content("Update id:" + id);
        }

        /// <summary>
        /// Add
        /// </summary>
        /// <param name="param">Add ids</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add(params string[] param)
        {
            return Content(string.Join(",", param));
        }
    }
}

原因:控制器中出现未被HTTP标记的方法

解决方案:删除该方法或者添加相应的HTTP标记

官网文档:https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.2&tabs=netcore-cli#add-and-configure-swagger-middleware

猜你喜欢

转载自www.cnblogs.com/xieyang07/p/10650595.html