一、创建ASP.Net Core Web API项目

1、在Visual Studio 2019中创建新项目,并选择Web模板中的“ASP.Net Core Web应用程序”。

在ASP.Net Core Web API中使用Swagger

2、在“配置新项目”对话框中输入项目名称、位置等信息。

在ASP.Net Core Web API中使用Swagger

3、选择应用程序框架(.Net Core)和版本(ASP.Net Core 3.1),选择应用程序模板(API)。为了简单起见,取消选中“高级”选项中的“为HTTPS配置”项。

在ASP.Net Core Web API中使用Swagger

二、Swagger配置

1、使用NuGet安装Swagger包(Swashbuckle.AspNetCore)

1.1 在VS2019的“工具”菜单栏中选择“NuGet 包管理器”,在右侧菜单中点击“管理解决方案的 NuGet 程序包”。

1.2 在弹出的“NuGet 解决方案”的“浏览”选项卡中输入Swashbuckle.AspNetCore,在输出列表中选择对应的包后安装。

在ASP.Net Core Web API中使用Swagger

2、在Startup类中注册Swagger服务

public void ConfigureServices(IServiceCollection services)
{
	//添加Swagger生成器
	services.AddSwaggerGen(options =>
	{
		//添加Swagger文档
		options.SwaggerDoc("V1", new OpenApiInfo()
		{
			Title = "test", //标题
			Version = "version-01", //版本
			Description = "ASP.Net Core Web API Swagger test" //描述
		});
	});

	services.AddControllers();
}

3、中间件中使用Swagger

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

	//启用Swagger中间件
	app.UseSwagger();
	app.UseSwaggerUI(options =>
	{
		//设置Swagger文档路径
		options.SwaggerEndpoint("/swagger/V1/swagger.json", "swagger test");
	});

	app.UseRouting();

	app.UseAuthorization();

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

三、运行项目

运行项目,在浏览器中输入http://localhost:52685/swagger/index.html,出现API文档页面。

在ASP.Net Core Web API中使用Swagger

四、总结

使用Swagger可以归纳为3个步骤:

1、安装Swagger包(Swashbuckle.AspNetCore)

2、注册Swagger服务

//添加Swagger生成器
services.AddSwaggerGen(options =>
{
	//添加Swagger文档
	options.SwaggerDoc("V1", new OpenApiInfo()
	{
		Title = "test", //标题
		Version = "version-01", //版本
		Description = "ASP.Net Core Web API Swagger test" //描述
	});
});

3、在中间件中使用Swagger

//启用Swagger中间件
app.UseSwagger();
app.UseSwaggerUI(options =>
{
	//设置Swagger文档路径
	options.SwaggerEndpoint("/swagger/V1/swagger.json", "swagger test");
});

分类:

技术点:

相关文章: