在asp.net core webapi 中开启swagger


首先需要安装包 Swashbuckle.AspNetCore

在asp.net core webapi 中开启swagger

接着在项目中右键属性

在asp.net core webapi 中开启swagger

在asp.net core webapi 中开启swagger

接着在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

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

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/281894.html

(0)
上一篇 2022年8月23日
下一篇 2022年8月23日

相关推荐

发表回复

登录后才能评论