在asp.net core webapi 中开启swagger

首先需要安装包 Swashbuckle.AspNetCore

接着在项目中右键属性

接着在Startup 文件中声明一个字段

private string currentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;

服务容器代码如下

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(option =>
            {
                option.SwaggerDoc(currentAssemblyName, new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Version = "v1",
                    Title = "在netcore3.1中,开启swagger",
                    Description = "这是文档描述",
                    Contact = new Microsoft.OpenApi.Models.OpenApiContact { Name = "syf", Email = "1010963984@qq.com" }
                });
                option.IncludeXmlComments(System.IO.Path.Combine(AppContext.BaseDirectory, $"{currentAssemblyName}.xml"), true);
            });
        }

管道中间件代码如下

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

  
            app.UseRouting();
            app.UseSwagger();
            app.UseSwaggerUI(option =>
            {
                option.SwaggerEndpoint($"/swagger/{currentAssemblyName}/swagger.json", "接口文档");

                option.DocumentTitle = "this is descrision";
            });
            app.UseAuthorization();

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

接着修改launchSettings.json文件,将launchUrl修改为swagger

 "openSwagger": {
      "commandName": "Project",
      "launchbrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentvariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }

抑制警告: 在项目文件的xml中添加 <Nowarn>$(Nowarn);1591</Nowarn>

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <GenerateDocumentationFile>True</GenerateDocumentationFile>
    <DocumentationFile>openSwagger.xml</DocumentationFile>
    <Nowarn>$(Nowarn);1591</Nowarn>
  </PropertyGroup>

更多配置内容可以参考官方文档

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念