【.net core 5.0】創建系統默認WebApi


前提條件:

  1、Visual Studio 2019 16.8 或更高版本

       2、NET 5.0 SDK 或更高版本

A、新建項目--WebApi,默認系統會勾選Enable OpenAPI Support

 

 

 B、創建完成后直接運行,就可以看到帶Swagger的文檔說明及調用界面了

 

 

C、添加XML注釋,讓方法名的注釋也能顯示在文檔中

  1、在“解決方案資源管理器”中右鍵單擊該項目,然后選擇“編輯 <project_name>.csproj”,在代碼中添加

  

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

        如下圖:

  

 

 

 

  2、在ConfigureServices的services.AddSwaggerGen代碼中添加如下代碼:

var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);

  如下圖:

  

 

   3、在對應的Controller方法上,添加Summary注釋,然后再次運行項目就可以看到了

  

 

 

 

 

關於更多配置可參考官網:

Swigger詳情配置:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-5.0&tabs=visual-studio

理由配置:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/controllers/routing?view=aspnetcore-5.0#attribute-routing-with-httpverb-attributes

依賴注入到視圖:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/views/dependency-injection?view=aspnetcore-5.0

依賴注入到控制器:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/controllers/dependency-injection?view=aspnetcore-5.0

 

單元測試控制邏輯:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/controllers/testing?view=aspnetcore-5.0

identityserver4:https://docs.identityserver.io/en/latest/index.html

 


免責聲明!

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



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