.NET Core3.1 WebApi 配置Swagger 超详细办法

起因是这样的

大概上个月的时候做的一个项目,想试试配置swagger,因为现有项目配置的swagger只有.NET Framework上配置过,core上的还要重新学,然后网上一堆教程,各个方法不同,这一配置就是两天,可苦死我了。到现在,又开了个新项目的时候,果断搭建swagger,结果发现好像不会搭了,要弄些啥来着???又浪费了一个小时回头看以前的项目,=-=,这还了得,我还是写成博客放上面吧

废话不多说,直接开始配置

首先安装NuGet包 Swashbuckle.AspNetCore
.NET Core3.1 WebApi   配置Swagger 超详细办法

紧接着 Startup 的代码

using Swashbuckle.AspNetCore.SwaggerUI;//要添加的命名空间

namespace Project.API
{
    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.AddControllers();

            services.AddSwaggerGen(config =>
            {
                config.SwaggerDoc("v1", new OpenApiInfo() { Title = "项目名称 Api", Version = "v1" });//项目名称填你的项目名称,下同
                config.CustomSchemaIds(type => type.FullName);
                config.IncludeXmlComments($"{AppDomain.CurrentDomain.BaseDirectory}/Project.API.xml");//Project.API 为你的项目名称
            });
            Register(services);

            services.AddOptions();


        }

        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="services"></param>
        private static void Register(IServiceCollection services)
        {


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseSwagger(c =>
            {
                c.RouteTemplate = "api-doc/{documentName}/swagger.json";//配置后,你的最终访问路径就就是 /api-doc/index.html
            });
            app.UseSwaggerUI(c =>
            {
                c.InjectJavascript("/zh_CN.js");//中文包,怎么测试也出不来,等待一个大佬解决下,所以这里就不放中文包了,因为根本用不了,(这句可以删
                c.ShowExtensions();
                c.DocExpansion(DocExpansion.None);
                c.RoutePrefix = "api-doc";
                c.SwaggerEndpoint("v1/swagger.json", "项目名称 Api v1");
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=ApiHome}/{action=Index}/{id?}");
            });
        }
    }
}

最后两步
你的项目-->右键属性-->生成事件-->生成后事件命令行--> copy $(TargetDir){项目名称}.xml $(ProjectDir){项目名称}.xml
.NET Core3.1 WebApi   配置Swagger 超详细办法

你的项目-->右键属性-->生成事件-->生成后事件命令行--> 输出 如图所示
.NET Core3.1 WebApi   配置Swagger 超详细办法

最后运行试试

记得切换端口号 https://localhost:{xxxx}/api-doc/index.html

.NET Core3.1 WebApi   配置Swagger 超详细办法

成功!!!