
新建项目

取消配置


下载NUget 包

修改startup
添加引用
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Reflection;
修改ConfigureServices方法里加入下面的代码,注册Swagger生成器,定义一个文档,设置xml文档的注释路径
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Version = "v1",
Title = "接口文档",
Description = "RESTful API"
});
// 为 Swagger 设置xml文档注释路径
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
}

修改Configure方法里加入下面的代码,启用中间件服务使用生成Swagger和SwaggerUI,将SwaggerUI中的RoutePrefix设为空字符串,这样就能在根节点(http://localhost:port)直接显示SwaggerUI界面。
//启用中间件服务生成Swagger
app.UseSwagger();
//启用中间件服务生成SwaggerUI,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web App V1");
c.RoutePrefix = string.Empty;//设置根节点访问
});

配置属性





