当前位置:网站首页>Swagger's asp Net core web API help page
Swagger's asp Net core web API help page
2022-06-30 15:40:00 【zhoubangbang1】
Use Web API when , Understanding its various approaches can be a challenge for developers . Swagger Also known as OpenAPI, Solved for Web API Generate useful documents and help page questions . It has features such as interactive documents 、 client SDK Generate and API Discoverability and other advantages .
Swashbuckle There are three main components :
1. Swashbuckle.AspNetCore.Swagger: take SwaggerDocument Object is exposed as JSON Of the endpoint Swagger Object model and middleware .
2. Swashbuckle.AspNetCore.SwaggerGen: From routing 、 Controllers and models are generated directly SwaggerDocument Object's Swagger generator . It is usually with Swagger Endpoint middleware combines , To make public automatically Swagger JSON.
3. Swashbuckle.AspNetCore.SwaggerUI:Swagger UI An embedded version of the tool . It explains Swagger JSON To build description Web API Feature customizable rich experience . It includes built-in testing tools for public methods .
add to Swashbuckle.AspNetCore Methods
1. from “ Package manager console ” window :
· go to “ View ” > “ Other windows ” > “ Package manager console ”
· Navigate to include .csproj File directory
· Please execute the following order :


Install-Package Swashbuckle.AspNetCore-Version 5.0.0-rc4
2. from “ management NuGet Package ” In the dialog box :
· Right click “ Solution explorer ” > “ management NuGet package ” Projects in China
· take “ BaoYuan ” Set to “nuget.org”
· Make sure that “ Including pre release ” Options
· Type in the search box “Swashbuckle.AspNetCore”
· from “ Browse ” Tab, select the latest “Swashbuckle.AspNetCore” package , And then click “ install ”
Add and configure Swagger middleware
take Swagger Add generator to Startup.ConfigureServices In the collection of services in the method :
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
} stay Startup.Configure In the method , Enable middleware for generation JSON Documentation and Swagger UI Provide services
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("./swagger/v1/swagger.json", "My API V1");
});
app.UseMvc();
}
Start the application , And navigate to the http://localhost:<port>/swagger/v1/swagger.json. The generated document describing the endpoint is displayed in Swagger standard (swagger.json) in .
Can be found in http://localhost:<port>/swagger find Swagger UI. adopt Swagger UI Browse API, And merge it into other plans .
At the root of the application (http://localhost:<port>/) Provided by Swagger UI, Please put RoutePrefix Property is set to an empty string :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("./swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
});
app.UseMvc();
}And will launchSettings.json In the document "launchUrl": "api/values" Comment out

{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:52655",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
//"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"appDemo": {
"commandName": "Project",
"launchBrowser": true,
//"launchUrl": "swagger",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}Customizations and extensions
Swagger Provides archiving and customization of the object model UI Options to match your theme .
API Information and instructions
Pass to AddSwaggerGen The configuration operation of the method adds such as author 、 License and description information :
public void ConfigureServices(IServiceCollection services){services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);services.AddSwaggerGen(c =>{c.SwaggerDoc("v1", new Info{Version = "v1",Title = "ToDo API",Description = "A simple example ASP.NET Core Web API",TermsOfService = "https://blog.csdn.net/zhoubangbang1",Contact = new Contact{Name = "zbb",Email = string.Empty,Url = "https://blog.csdn.net/zhoubangbang1",},License = new License{Name = "Use under LICX",Url = "https://blog.csdn.net/zhoubangbang1",}});});}
Running results :

Add comments to the interface
take Swagger Is configured to use the... Generated as described above XML file . about Linux Or not Windows operating system , File names and paths are case sensitive . for example ,“TodoApi.XML” The file in Windows On the effective , But in CentOS The invalid .
Right click Project name => attribute => Generate , Check “ Output ” Below “xml Document file ”, The system will generate a by default , Of course the old rule , You can also name yourself :
Here I use the relative path , Can be generated directly to api Layer of bin Under the folder

public void ConfigureServices(IServiceCollection services){services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);services.AddSwaggerGen(c =>{c.SwaggerDoc("v1", new Info{Version = "v1",Title = "ToDo API",Description = "A simple example ASP.NET Core Web API",TermsOfService = "https://blog.csdn.net/zhoubangbang1",Contact = new Contact{Name = "zbb",Email = string.Empty,Url = "https://blog.csdn.net/zhoubangbang1",},License = new License{Name = "Use under LICX",Url = "https://blog.csdn.net/zhoubangbang1",}});// This is itvar basePath = PlatformServices.Default.Application.ApplicationBasePath;var xmlPath = Path.Combine(basePath, " appDemo.xml");// This is what we just configured xml file namec.IncludeXmlComments(xmlPath, true);// The default second parameter is false, This is controller Notes , Remember to revise});}
here , Don't get busy running the project yet , There will be a lot of warnings
This is because swagger Pass some interface methods xml File configuration .
If you don't want to annotate every method like this , It can be configured like this ( Configure the current project , Warnings can be ignored , Remember to put a semicolon behind it ;1591):
The final run result :

Please pay attention to my WeChat official account , Let's make progress together :

边栏推荐
- A. Theatre Square(codefore)
- Policy Center-User Data
- Technology sharing | anyrtc service single port design
- String connector
- Flask Sqlalchemy - how to use custom query criteria ---orm (7)
- My own opinion on lisp
- The short video and live broadcast incubation training camp with goods opens nationwide enrollment!
- Specific steps for installing mysql8.0 on Windows system
- Rte2021 review HDR technology product practice and exploration
- Talk about why I started technical writing
猜你喜欢

终于看懂科学了!200张图领略人类智慧的巅峰

Map reduce case super detailed explanation

【子矩阵数量统计】CF1181C Flag子矩阵数量统计

【Leetcode】链表排序(逐步提高时空复杂度)

消息队列十连问

Kubernetes: a comprehensive analysis of container choreography

Message queue ten questions

It's so brain - burning that no wonder programmers lose their hair

Super comprehensive redis distributed high availability solution: sentry mechanism

Policy Center > Device and Network Abuse
随机推荐
The principle of fluent 2 rendering and how to realize video rendering
Imeta | Ye Mao / Shi Yu reviewed the dynamic shuttle and ecological function of intracellular and extracellular genes in the environmental microbiome
Policy Center > Malware > Malware
1058 a+b in Hogwarts (20 points)
Chapter 2 installation and use of vscode editor
4.8 data type conversion
Abstract meaning
数数据可视化实战案例(timeline轮播图,streamlit 控件年份 metabase可视化使用教程)2.0
Policy Center-User Data
Xiao Sha's pain (thinking problem)
国债逆回购在哪个平台上买比较安全?
String connector
Specific steps for installing mysql8.0 on Windows system
(Niuke) BFS
Kubernetes: a comprehensive analysis of container choreography
Chapter III installation and use of jupyter
[matlab] 3D drawing summary
4.6 floating point number
【子矩阵数量统计】CF1181C Flag子矩阵数量统计
Policy Center > Deceptive Behavior