.Net Core3.1下用Swagger搭建web api(1)

基于.net core 3.1建一个web api的项目

先下载.net core 3.1的SDK(开发.net core项目时会用到)和Runtime(用来运行.net core的应用程序)

地址:https://dotnet.microsoft.com/download/visual-studio-sdks?utm_source=getdotnetsdk&utm_medium=referral

1 创建ASP.NET Core web项目

2 引入Swashbuckle.AspNetCore程序包

执行以下命令

Install-Package Swashbuckle.AspNetCore -Version 5.0.0-rc4

添加 并配置Swagger中间件

   public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //注册swagger
            services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1.0", new OpenApiInfo { Title = "1", Version = "1.0" });
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                    c.IncludeXmlComments(xmlPath);
                });
           
        }
  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            //Swagger规范和Swagger UI
            app.UseSwagger();
            app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "1");
                    c.RoutePrefix = string.Empty;
                });
               

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

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

地址栏改一下

index.html

如果对接口做了xml注释,要在Startup添加如下代码,才可以显示出来

先引入NuGet包:Microsoft.Extensions.PlatformAbstractions

然后右键属性

再在Startup中添加下面的代码

 var basePath = PlatformServices.Default.Application.ApplicationBasePath;
 //Core.Admin.webapi.xml是我的项目生成XML文档的后缀名,具体的以你项目为主
 var xmlPath = Path.Combine(basePath, "Core.Admin.webapi.xml");
 c.IncludeXmlComments(xmlPath);

运行项目,注释已经出来了

在launchSettings.json中更改一下launchUrl这个环境变量 index.html

你可能感兴趣的:(.Net Core3.1下用Swagger搭建web api(1))