.net core 配置swagger


首先要現有一個asp.net  webApi項目 這里就不贅述了,接下來就按下面的步驟進行即可(本文是基於swagger 1.0.0-rc3版本的配置)

1.在project.json中添加 swagger的包名   "Swashbuckle.AspNetCore": "1.0.0-rc3",

   保存后vs會自動下載swagger的包 這個可能會需要一定的時間 

2.在status.cs中添加swagger的相關配置

public void ConfigureServices(IServiceCollection services)
{
       services.AddSwaggerGen(options => {

         options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
          {
                Version = "v1",
                Title = " API 文檔",
                Description = "by bj eland"
       });

  //ApiKeyScheme/BasicAuthScheme/OAuth2Scheme/SecurityScheme
  //options.AddSecurityDefinition("Bearer", new ApiKeyScheme
    //{
    // //Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
    // Name = "Authorization",
    // In = "header",
    // Type = "apiKey"
    //});
  // options.OperationFilter<HttpHeaderFilter>();

  });
  services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{

  app.UseMvc();

  app.UseSwagger();
  app.UseSwaggerUI(c =>
    {
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
    c.DocExpansion("none");
  });

}

3.項目的屬性文件中  設置 "launchUrl": "swagger",
右擊啟動項目選擇屬性->Debug->launchUrl   :  swagger

配置完成了,運行項目試試吧

 

注意:

1.controller中所有的方法都必須添加 [HttpGet]、[HttpPost]....這樣的屬性

2.同一個controller中相同的屬性不能同時存在多個

3.當swagger加載失敗的時候,關閉VS2015到項目文件中刪除.vs文件,重新打開解決方案,重新添加swagger包。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM