搜Swashbuckle.AspNetCore
在NuGet 中,安裝 Swashbuckle.AspNetCore :
我使用的版本爲 : 5.0.0-rc2ios
Ⅰ : Startup.cs
① ,ConfigureServices方法中:json
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(options => { options.SerializerSettings.Formatting = Formatting.Indented; }); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo() { Title = "Swagger Test UI", Version = "v1", Description = "Aonaufly first ASP.NET Core Web API" }); options.CustomSchemaIds(type => type.FullName); // 解決相同類名會報錯的問題 options.IncludeXmlComments(Path.Combine(Directory.GetCurrentDirectory(), "WebAPIPoco.xml")); // 標註要使用的 XML 文檔 options.DescribeAllEnumsAsStrings(); }); }
②:Configure中api
// 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 { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //設置全局跨域 app.UseCors(builder => builder.AllowAnyOrigin()); app.UseHttpsRedirection(); app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; }); // 在這裏面能夠注入 app.UseSwaggerUI(options => { options.ShowExtensions(); options.ValidatorUrl(null); options.SwaggerEndpoint("/swagger/v1/swagger.json", "Aonaufly API V1"); options.DocExpansion(DocExpansion.None); }); app.UseMvc(); }
①,處處項目XML , 加入1591禁止警告
②,將項目XML生成路徑複製到項目根路徑
copy $(TargetDir)WebAPIPoco.xml $(ProjectDir)WebAPIPoco.xml
③,重置默認網頁爲swagger , 默認是 api/values
跨域
/// <summary> /// 帶參數的get請求 /// </summary> /// <remarks> /// <code> /// 輸入 : int /// 輸出 : string /// </code> /// </remarks> /// <param name="id">ID號</param> /// <returns>String</returns> /// <response code="201">返回字符串</response> /// <response code="400">若是id爲空</response> // GET api/values/5 [HttpGet("{id}")] [ProducesResponseType(201)] [ProducesResponseType(400)] public ActionResult<string> Get(int id) { return "value"; }
結果:
app