1. NuGet 中添加 Swashbuckle.AspNetCorejavascript
2.添加 Startup 信息java
將 Swagger 生成器添加到 Startup.ConfigureServices 方法中的服務集合中:json
//註冊Swagger生成器,定義一個和多個Swagger 文檔 services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); });
在 Startup.Configure
方法中,啓用中間件爲生成的 JSON 文檔和 Swagger UI 提供服務:c#
//啓用中間件服務生成Swagger做爲JSON終結點 app.UseSwagger(); //啓用中間件服務對swagger-ui,指定Swagger JSON終結點 app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); });
3.調試默認頁app
4.xml 註釋信息 1591 忽略註釋警告,xml 在bin 目錄下,xml名與項目名相同。oop
5.添加特定參數,(query header body path formData)各個 報文均可以配, 功能強大。ui
新建 class 實現 配置類 IOperationFilterthis
public class SwaggerHeaderOperation : IOperationFilter
{
/// <summary>
///
/// </summary>
/// <param name="operation"></param>
/// <param name="context"></param>
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null) operation.Parameters = new List<IParameter>();
var attrs = context.ApiDescription.ActionDescriptor.AttributeRouteInfo;
//先判斷是不是匿名訪問,
var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
{
var actionAttributes = descriptor.MethodInfo.GetCustomAttributes(inherit: true);
bool isAnonymous = actionAttributes.Any(a => a is AllowAnonymousAttribute);
//非匿名的方法,連接中添加accesstoken值
if (!isAnonymous)
{
operation.Parameters.Add(new NonBodyParameter()
{
Name = "accesstoken",
In = "header",//query header body path formData
Type = "string",
Required = false //是否必選
});
}
}
}
}spa
在 中添加 IServiceCollection.OperationFilter<SwaggerHeaderOperation>(); 調試
Startup 最終配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//全局配置Json序列化處理
services.AddMvc()
.AddJsonOptions(options =>
{
//忽略循環引用
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//不使用駝峯樣式的key
//options.SerializerSettings.ContractResolver = new LowercaseContractResolver();
//設置時間格式
options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
}
);
services.AddSwaggerGen(c =>
{ // 爲 Swagger JSON and UI設置xml文檔註釋路徑
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//獲取應用程序所在目錄(絕對,不受工做目錄影響,建議採用此方法獲取路徑)
var xmlPath = Path.Combine(basePath, "AsnycCoreAPI.xml");
c.IncludeXmlComments(xmlPath);
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.OperationFilter<SwaggerHeaderOperation>();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
//啓用中間件服務生成Swagger做爲JSON終結點
app.UseSwagger();
//啓用中間件服務對swagger-ui,指定Swagger JSON終結點
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
最後祝你們 國慶節愉快。