ASP.NET Core Swagger

Swagger/OpenAPI 的 ASP.NET Core Web API 帮助页
查看或下载示例代码
Swagger转Word文档
GitHub - Swagger API 文档 转 Word 文档的工具项目

1、管理 NuGet 程序包
     Swashbuckle.AspNetCore
【注意:在添加引用 Swashbuckle.AspNetCore 时,选中“包括预发行版”】

2、包安装

【WebAPI项目】【右键】【属性】

3、Startup.cs
     将 Swagger 生成器添加到 Startup.ConfigureServices 方法中的服务集合中

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));

    //services.AddControllers();

    //转换为应用程序
    services.AddControllers(options =>
    {
        //options.UseCentralRoutePrefix(new RouteAttribute($"api")); //普通网站
        options.UseCentralRoutePrefix(new RouteAttribute($""));    //转换为应用程序
    })

    // core 3.0 写法 new OpenApiInfo
    services.AddScoped<SwaggerGenerator>();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });

        #region 添加方法注释
        var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
        var xmlPath = Path.Combine(basePath, "Asset.WebAPI.xml");
        c.IncludeXmlComments(xmlPath, true);

        /// .net6
        var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);

        #endregion

        #region 添加header参数
        var securityScheme = new OpenApiSecurityScheme()
        {
          Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
          Name = "Authorization",
          In = ParameterLocation.Header,
          Type = SecuritySchemeType.Http,
          Scheme = "bearer",
          BearerFormat = "JWT"
        };
        var securityRequirement = new OpenApiSecurityRequirement
        {
          {
            new OpenApiSecurityScheme{Reference = new OpenApiReference{Type = ReferenceType.SecurityScheme,Id = "bearerAuth"}},
            new string[] {}
          }
        };
        #endregion
    });

    // core 2.2 写法 new Swashbuckle.AspNetCore.Swagger.Info
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "My API", Version = "v1" });
    });
}

4、Startup.cs
     在 Startup.Configure 方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务

public void Configure(IApplicationBuilder app)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.

#if DEBUG
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        c.DocumentTitle = "Asset 在线文档调试";
    });
#else
    // 转换为应用程序
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint($"/{Configuration["AppSettings:VirtualPath"]}/swagger/v1/swagger.json", "My API V1");
        c.DocumentTitle = "Asset 在线文档调试";
    });
#endif

    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

5、appsettings.json

  "AppSettings": {
    //"VirtualPath": ""   //普通网站
    "VirtualPath": "Api"  //转换为应用程序
  }

6、添加方法注释说明
选中【Asset.WebAPI】项目,新增【Asset.WebAPI.xml】文件
选中【Asset.WebAPI】项目右键 - 属性 - 生成 - 输出 - XML 文档文件


7、打开 Web 项目文件夹,编辑 WebAPI.csproj 文件

<PropertyGroup>
  <GenerateDocumentationFile>True</GenerateDocumentationFile>
</PropertyGroup>

或 WebAPI\Properties\PublishProfiles\FolderProfile.pubxml 文件

<?xml version="1.0" encoding="utf-8"?>

<Project>
	<PropertyGroup>
		<GenerateDocumentationFile>True</GenerateDocumentationFile>
	</PropertyGroup>
</Project>

8、启动应用
     浏览器输入 http://localhost:<port>/swagger/v1/swagger.json 生成的描述终结点的文档显示。
     浏览器输入 http://localhost:<port>/swagger/index.html 找到 Swagger UI。

9、启动应用(转换为应用程序)
     浏览器输入 http://localhost:<port>/api/swagger/v1/swagger.json 生成的描述终结点的文档显示。
     浏览器输入 http://localhost:<port>/api/swagger/index.html 找到 Swagger UI。

10、IIS目录(转换为应用程序)

*
*
*

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值