Net Core教程

在asp.net core webapi 中开启swagger

本文主要是介绍在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>

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

这篇关于在asp.net core webapi 中开启swagger的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!