二、搭建Swagger
阅读原文时间:2023年07月16日阅读:1

1、新建.netCore webapi项目

2、安装swagger ,通过 Package Manager 控制台:Install-Package Swashbuckle.AspNetCore

3、修改Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace CoreTest
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        //1、注册服务Swagger  
        services.AddSwaggerGen(options =>  
        {  
            options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info  
            {  
                Version = "v1",  
                Title = "My API",  
                Description = "by JiaJia"  
            });  
        });  
    }  
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
    {  
        if (env.IsDevelopment())  
        {  
            app.UseDeveloperExceptionPage();  
        }  
        else  
        {  
            app.UseHsts();  
        }  
        app.UseHttpsRedirection();  
        app.UseMvc();

        //2、添加到管道  
        #if DEBUG  
        app.UseSwagger();  
        app.UseSwaggerUI(c =>  
        {  
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");  
            // c.DocExpansion(DocExpansion.None);  
        });  
        #endif  
    }  
}  

}

4、访问 Swagger UI 地址

http://localhost:60238/swagger/index.html

5、添加备注

1、在项目属性的 生成 => 输出 中勾选 XML文档文件。

2、在 Start.cs => ConfigureServices 方法中的 AddSwaggerGen 处增加 IncludeXmlComments 处理。

//1、注册服务Swagger
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
{
Version = "v1",
Title = "My API",
Description = "by JiaJia"
});
//在 Start.cs => ConfigureServices 方法中的 AddSwaggerGen 处增加 IncludeXmlComments 处理。
options.IncludeXmlComments(string.Format("{0}/CoreTest.xml",
AppDomain.CurrentDomain.BaseDirectory));

/\*或者这种添加方式//为 Swagger JSON and UI设置xml文档注释路径  
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)  
var xmlPath = Path.Combine(basePath, "CoreTest.xml");//和项目名对应  
options.IncludeXmlComments(xmlPath);\*/  

});

3、控制器对Action添加注释信息

///

/// 根据ID获取用户信息 ///
/// 用户ID
/// 用户信息
[HttpGet("{id}")]
public ActionResult Get(int id)
{
return "user info";
}

运行报错:

原因:生成的xml文件,路径不对,导致的/swagger/v1/swagger.json提示报错。

解决方案:(指定输出路径默认空白,需要填写:bin\Debug\),而且默认的(CoreTest.xml)xml文件,与Startup的文件必须对应。

最终效果:

4、不想每一个方法都这么加注释,可以这么配置(对当前项目进行配置,可以忽略警告,记得在后边加上分号 ;1591):

搭建MiniProfiler

1、引入nuget包:

Install-Package MiniProfiler.AspNetCore.Mvc

2、然后,在startup.cs 中配置服务ConfigureServices:

//注册服务MiniProfiler
services.AddMiniProfiler(options =>
{
options.RouteBasePath = "/profiler";//注意这个路径要和下边 index.html 脚本配置中的一致,
(options.Storage as MemoryCacheStorage).CacheDuration = TimeSpan.FromMinutes();
});

3、最后,调用下中间件即可:

//调用MiniProfiler中间件
app.UseMiniProfiler();

当前这个时候还不能使用,我们还需要在 Swagger 中进行配置,以便它能在 swagger 中使用。

在 Swagger 中配置 MiniProfiler

上边我们在配置中已经启动了服务,接下来就需要设置如何在 swagger 中展示了,这个时候我们就需要自定义我们的swagger主页了,以前我们是用的默认的index.html,现在咱们需要自定义一个:

从官网 Github 上,下载最新的 index.html:https://github.com/swagger-api/swagger-ui/blob/master/dist/index.html






%(DocumentTitle)