李奕憲
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- slideOptions: showNotes: false --- # .Net Core Web API 基本教學 --- ## 基本簡介 ---- ### 什麼是 .Net Core * 微軟開發的第一個<span style="color:red">跨平台</span>的應用程式開發框架 * 為 <span style="color:red">.NET 5 +</span> 之前版本的名稱 * .NET Core 1.0、1.1、2.0、2.1、2.2、3.0、3.1 * .NET 5、6 Note: * 為甚麼使用 3.1 * .NET 6 為較新版本,資源可能相對較少 * .NET 5 並不是長期支援版本,到今年 5 月 * 直接跳 .NET 5 避免跟 .NET Framework 4.X 搞混 ---- ### .Net Core 與 .NET Framework * <span style="color:red">.Net Core</span> 是 .NET Framework 的<span style="color:red">新一代版本</span> * .NET Framework 最新版本到 <span style="color:red">4.8</span> * 運行環境 * .NET Core 能在 <span style="color:red">Windows</span>、<span style="color:red">MacOS</span>、<span style="color:red">Linux</span> 上運行 * .NET Framework 只能在 <span style="color:red">Windows</span> 上運行 * .NET Core 會包含 .NET Framework 的類別庫 --- ## 安裝 SDK 與 Runtime Note: * 下載位置 : [Download .NET](https://dotnet.microsoft.com/en-us/download/dotnet) ---- ### SDK ( 用於<span style="color:red">開發建置</span> ) ![](https://i.imgur.com/q3hICKx.png) Note: * 本身包含 Runtime ---- ### Runtime ( 用於<span style="color:red">執行</span> ) ![](https://i.imgur.com/aPhMzgG.png) Note: * IIS 上執行須安裝 Hosting Bundle,包含 IIS runtime support --- ## 建立新專案 ---- ### Visual Studio 2022 ![](https://i.imgur.com/4YoGuUi.png) ---- ![](https://i.imgur.com/5ttyxuF.png) ---- ### Visual Studio Code ```shell= dotnet new webapi -o NETCoreWebAPITest ``` Note: * 在要放專案的目錄下執行此命令,例如 : source\repos\ * 或是建立專案名稱資料夾執行 `dotnet new webapi` --- ## 專案內容 ---- ### 檔案架構 ![](https://i.imgur.com/rAywGTB.png) * 相依性 : <span style="color:red">組件參考</span>、<span style="color:red">NuGet</span> * Controller : 控制器,用於<span style="color:red">處理 Web API 要求</span> * Program.cs : 程式的<span style="color:red">進入點</span> * Startup.cs : 負責<span style="color:red">基礎設定檔</span>的執行 Note: * 相依性 * 相依性的組件參考設定會記錄在 .csproj 中 * Controller * Controllers 主要處理路由、回應格式、寫 LOG * 另外註冊 Service 注入 Controller 來處理邏輯 * WeatherForecast.cs 可以放在 Models 資料夾裡 ---- ### 程式架構 #### Program.cs ![](https://i.imgur.com/q5pMYgf.png) * 呼叫 <span style="color:red">CreateHostBuilder</span> 建立 Web 的預設組態環境並載入 Startup Note: * 參考 : [ASP.NET Core 中的 .NET 泛型主機](https://docs.microsoft.com/zh-tw/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.1) * 以前用 IWebHostBuilder,現在建議都用 IHostedBuilder 了 ---- #### Startup.cs : ConfigureServices ![](https://i.imgur.com/izwxFtD.png) * 由 Runtime 呼叫,<span style="color:red">負責向容器註冊 Service</span> * 一旦註冊了,所有類別都<span style="color:red">能向容器獲取此實例</span> * 註冊時<span style="color:red">可以決定該實例的生命週期</span>,分為三種 * AddTransient * AddScoped * AddSingleton Note: * 參考 : [ASP.NET Core 中的應用程式啟動](https://docs.microsoft.com/zh-tw/aspnet/core/fundamentals/startup?view=aspnetcore-3.1)、[.NET Core 中的相依性插入](https://docs.microsoft.com/zh-tw/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1) * AddTransient : 週期為每次請求到請求結束,每次請求都是一個新的實例 * AddScoped : 週期為客戶端的連結到結束 * AddSingleton : 週期為應用程序的開始到結束,每個請求都使用相同實例 ---- #### Startup.cs : Configure ![](https://i.imgur.com/ERWx684.png) * 由 Runtime 呼叫,<span style="color:red">負責指定應用程式如何響應請求</span> * 可在此插入<span style="color:red">中介軟體</span> Note: * 參考 : [ASP.NET Core 中介軟體](https://docs.microsoft.com/zh-tw/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1) * UseDeveloperExceptionPage : 回報應用程式執行階段錯誤 * UseHttpsRedirection : 會將 HTTP 要求重新導向到 HTTPS * UseRouting : 路由要求 * UseAuthorization : 授權使用者存取安全資源 * UseEndpoints : 將呼叫端點引導至要求方法 ---- ### Controller 如何使用 Service ---- #### 加入 Service ```csharp= public void ConfigureServices(IServiceCollection services) { ... services.AddSingleton<TestService>(); ... } ``` * Startup.cs : ConfigureServices ---- #### 使用 Service ```csharp= public class WeatherForecastController : ControllerBase { ... private TestService _service; public WeatherForecastController(TestService service) { _service = service; } ... } ``` * Controller ---- ### 路由 * 透過路由才能讓應用程式知道此次請求須<span style="color:red">交由哪個方法處理</span> * 為了<span style="color:red">讓使用者明瞭 API 是做甚麼的</span>,路由的設計也很重要 Note: * 參考 : [ASP.NET Core 中的路由](https://docs.microsoft.com/zh-tw/aspnet/core/fundamentals/routing?view=aspnetcore-3.1) ---- #### 在 Controller <span style="color:red">類別</span>套用屬性 ```csharp= [Route("[controller]")] public class WeatherForecastController : ControllerBase { ... } ``` * 常用屬性 : <span style="color:red">controller</span>、<span style="color:red">action</span> * 使用純文字或是和屬性<span style="color:red">混合使用</span>,例如 : ```csharp= [Route("api/[controller]/[action]")] ``` ---- #### 在 Action <span style="color:red">方法</span>套用屬性 ```csharp= [HttpGet] public IEnumerable<WeatherForecast> Get() { ... } ``` * 決定 HTTP 協議中<span style="color:red">傳送請求的方式</span> * HttpGet、HttpPost、HttpDelete、HttpPut * 接著加上路由,例如 : ```csharp= [HttpGet("product/{id:int}")] ``` * 不使用路由傳遞 : GET .../product?id=1 --- ## 套件分享 ---- ### Swagger * 透過產生器就可<span style="color:red">自動生成 API 文件</span>供對接者查看 * 也能透過文件進行<span style="color:red">線上測試</span> ```shell= Install-Package Swashbuckle.AspNetCore -Version 6.2.3 ``` Note: * 參考 : [Swashbuckle 與 ASP.NET Core 使用者入門](https://docs.microsoft.com/zh-tw/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio) ---- #### Startup.cs : ConfigureServices ![](https://i.imgur.com/JCUAJoC.png) * Swagger 產生器,<span style="color:red">可產生一到多份檔案</span> * 產生 <span style="color:red">XML 檔</span> ---- #### <span style="color:red">註解</span>可以在文件上更<span style="color:red">詳細描述 API</span> ![](https://i.imgur.com/IvmFdH5.png) ![](https://i.imgur.com/lxhd3oq.png) Note: * 可以設定回傳格式、描述回應類型、要求範例... ---- #### Startup.cs : Configure ![](https://i.imgur.com/DXjcp7j.png) * <span style="color:red">UseSwagger 產生 JSON 檔</span>,位置 : /swagger/v1/swagger.json * <span style="color:red">UseSwaggerUI 產生網頁</span>,位置 : /swagger/index.html ---- ### NLog * 依日期時間<span style="color:red">記錄 Log</span> * 方便<span style="color:red">日後維護</span>或<span style="color:red">查看歷史呼叫紀錄</span> ```shell= Install-Package NLog -Version 4.7.15 Install-Package NLog.Web.AspNetCore -Version 4.14.0 ``` Note: * 參考 : [Getting started with ASP.NET Core 3](https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3) ---- #### 建立 nlog.config ![](https://i.imgur.com/FBXCYZM.png) * 包含<span style="color:red">加入 .net core 擴展</span>、<span style="color:red">設定目標</span>、<span style="color:red">設定規則</span> Note: * 參考 : [Configuration file](https://github.com/NLog/NLog/wiki/Configuration-file) ---- #### nlog.config 啟用複製 ![](https://i.imgur.com/1jRNsIb.png) Note: * 在發佈時,才會將設定好的 nlog.config 帶過去 ---- #### program.cs ![](https://i.imgur.com/cpQl3LX.png) ---- #### appsettings.json ![](https://i.imgur.com/ROFW0jP.png) * 這邊的 Default <span style="color:red">會覆蓋 nlog.config 的 minievel</span> Note: * 若這邊設定的層級較高,nlog.config 那邊的層級設為較低也不會記錄該層級 ---- #### 如何使用 ```csharp= private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; _logger.LogDebug("NLog injected into WeatherForecastController"); } ``` * LogCritical、LogError、LogWarning、LogInformation、LogDebug、LogTrace Note: * Critical : 致命 * Error : 錯誤 * Warning : 警告 * Information : 資訊 * Debug : 偵錯 * Trace : 追蹤 ---- ### 統一回復錯誤格式 * 避免使用者看到錯誤細節,方便其處理錯誤 ---- #### Startup.cs : Configure ```csharp= public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Unite/Error"); } } ``` ---- #### ErrorController ![](https://i.imgur.com/dCjF9Vi.png) --- ## 建置與執行 ---- ### Visual Studio Code 建置 ```shell= dotnet build ``` 建置與執行 ```shell= dotnet run ``` 建置與執行並監看檔案 ```shell= dotnet watch run ``` Note: * 預設網址為 : https://localhost:5001、http://localhost:5000/ * 可在 `Properties` > `launchSettings.json` 更改 --- ## 佈署 ---- ### 資料夾 * 只需將<span style="color:red">發佈出來的資料夾內容</span>放入<span style="color:red">站點的實體路徑</span>即可 ---- #### Visual Studio ![](https://i.imgur.com/uPDdRnc.png) ---- ![](https://i.imgur.com/TbGFewO.png) ---- ![](https://i.imgur.com/rJTNiya.png) Note: * 新增 : 新增設定檔 * 更多動作 : 重新命名、編輯、刪除 ---- #### Visual Studio Code ```shell= dotnet publish --configuration Release ``` * 路徑 : .\bin\Release\netcoreapp3.1\publish ---- ### 網頁伺服器 ( IIS ) ![](https://i.imgur.com/aM81Xh3.png) * 透過 Web Platform Installer 安裝 Web Deploy Note: * 參考 : [設定 Web Deploy 發行的網頁伺服器 (Web Deploy 處理常式) - 建立和設定 IIS 網站](https://docs.microsoft.com/zh-tw/aspnet/web-forms/overview/deployment/configuring-server-environments-for-web-deployment/configuring-a-web-server-for-web-deploy-publishing-web-deploy-handler#create-and-configure-an-iis-website) * 下載位置 : [Web Platform Installer](https://www.microsoft.com/web/downloads/platform.aspx) * 沒有看到佈署按鈕 : * 需安裝 `Web Deploy 3.6`、`Web Deploy 3.6 without bundled SQL support`、`Web Deploy 3.6 for Hosting Servers` * `開啟或關閉 Windows 功能` 需開啟 `IIS 管理服務` * 確認 `Web Deployment Agent Service`、`Web Management Service` 兩個服務有開啟 * `控制台/程式集/程式和功能` 中的 `Microsoft Web Deploy 3.6` 變更查看功能是否都有開啟 ---- ![](https://i.imgur.com/t1Z40vc.png) Note: * 可選擇其他身分或在 IIS 上建立使用者來避免發佈人員直接擁有管理者權限 * `指定發行伺服器連線的 URL` 須記下來 ---- #### Visual Studio 2022 ![](https://i.imgur.com/uw6SoBE.png) ---- ![](https://i.imgur.com/2ZddpmE.png) ---- ![](https://i.imgur.com/J9fZXoV.png) Note: * `目的地 URL` 為 IIS 上設定的 `指定發行伺服器連線的 URL` --- ## Q&A ---- ###### tags: `筆記` `簡報` `.Net Core` `WebAPI` `IIS`

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully