Code Monkey home page Code Monkey logo

dotnet7-core-template's Introduction

DotNet 7 Template

這份檔案將會說明如何從這個模板中開始新的後端解決方案

使用前

  1. 請先關閉 Visual Studio 後,將資料夾名稱重新命名
  2. 以 Visual Studio 重新開啟專案,並針對 Api 專案中 ProjectReference 的路徑做修改

    若找不到此宣告,則可跳過這步驟

  3. 將 API、Repository 專案名稱重新命名
  4. 針對專案點選右鍵 -> 同步命名空間
  5. 修改 build-push-deploy.yml 檔中的 DotNet7.Template.Api/DockerfileDotNet7.Template.Api 修改為正確的專案名稱
  6. 確認各類別與介面的命名空間是否正確
  7. 若有需要,可以修改 appsettings.Development.jsonSwagger.RoutePrefix 設定,此用途為設定 API 路徑前綴

另外,若 Visual Studio 將檔案儲存成 UTF-8 With BOM 會造成問題,請依據以下步驟設定:

  1. 安裝 Fix File Encoding 延伸模組
  2. 打開 工具 > 選項 > 左側選單選擇 Fix File Encoding
  3. 在右側 UTF8 without signature files regex 輸入框中輸入 \.(.+)$ 全部套用
  4. 按下確定完成

appSettings.json

如需使用資料庫,請打開 Extensions/DatabaseExtension.cs 將註解全部打開,並修改 DBContext 名稱為正確的名稱,同時請將資料庫連線字串、資料庫帳號與密碼設定完成,否則專案將無法啟動

Service 與 Repository 類別與介面綁定

Service 與 Repository 的類別與介面需進行綁定,否則 DI 將無法正常注入

  1. 打開 Extensions/ServiceMapperExtension.cs,依據範例將類別與介面綁定起來

Repository 專案設定

  1. 先將 Repository 專案設定為啟動專案

  2. 使用以下指令將指定資料庫中的資料表進行反向工程,建立出 Model 物件

    Scaffold-DbContext "Server=<SERVER_URI>; Port=<SERVER_PORT>; Database=<DATABASE_NAME>; User ID=<DATABASE_USERNAME>; Password=<DATABASE_PASSWORD>" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -ContextDir DBContexts -Tables <TABLE_NAME> -Project <REPOSITORY_PROJECT_NAME> -Force -NoOnConfiguring
  3. 打開 Extensions/DatabaseExtension.cs,將最下方的註解打開,並將 DBContext 修改為正確的類別

    若有多個 DBContext 也請在這邊一並宣告

  4. 將 Api 專案設定為啟動專案

AutoMapper Profile 宣告

  1. AutoMapperProfiles 資料夾下新增一個 任意名稱的 Profile 類別
  2. 在類別中宣告需要進行 Mapper 的類別綁定

環境變數

ASP.Net 取用設定名稱常使用 : 作為階層的分隔,但許多系統並不支援於環境變數名稱中包含 : 字符,因此可以 __ (雙底線) 取代 :,其內部會自動做轉換。

正式機也可使用 Swagger

若需要於正式機器上使用 Swagger,請打開 Program.cs,將

if (app.Environment.IsDevelopment())
{
    app.UseSwagger(config =>
    {
        string? path = app.Configuration.GetValue<string>("Swagger:RoutePrefix");
        if (!string.IsNullOrEmpty(path))
        {
            config.PreSerializeFilters.Add((swaggerDoc, httpRequest) =>
            {
                string httpScheme = (app.Environment.IsDevelopment()) ? httpRequest.Scheme : "https";
                swaggerDoc.Servers = new List<OpenApiServer> {
                    new OpenApiServer { Url = $"{httpScheme}://{httpRequest.Host.Value}{path}" }
                };
            });
        }
    });
    app.UseSwaggerUI();
}

修改為

//if (app.Environment.IsDevelopment())
//{
    app.UseSwagger(config =>
    {
        string? path = app.Configuration.GetValue<string>("Swagger:RoutePrefix");
        if (!string.IsNullOrEmpty(path))
        {
            config.PreSerializeFilters.Add((swaggerDoc, httpRequest) =>
            {
                string httpScheme = (app.Environment.IsDevelopment()) ? httpRequest.Scheme : "https";
                swaggerDoc.Servers = new List<OpenApiServer> {
                    new OpenApiServer { Url = $"{httpScheme}://{httpRequest.Host.Value}{path}" }
                };
            });
        }
    });
    app.UseSwaggerUI();
//}

另外,若正式機使用的網址包含有自訂的路徑 (例如: ingress 設定),請將該路徑加入 Swagger__RoutePrefix 環境變數中

若正式機未使用 TLS,請打開 Program.cs 並找到

string httpScheme = (app.Environment.IsDevelopment()) ? httpRequest.Scheme : "https";

將之修改為

string httpScheme = (app.Environment.IsDevelopment()) ? httpRequest.Scheme : "http";

Middlewares

請參考這篇文章

如果需要將資料傳遞到 Controller 中,可以利用 context.HttpContext.Items 當作傳遞方法。

  1. Middlewares 資料夾下建立 Middleware

    這邊使用 ExampleMiddleware 當作範例

    namespace DotNet7.Template.Api.Middlewares
    {
        public class ExampleMiddleware
        {
            private readonly RequestDelegate _next;
    
            public ExampleMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task Invoke(HttpContext context)
            {
                // 在處理請求「前」要先執行的程式
    
                await _next(context);
    
                // 在處理請求「後」要先執行的程式
            }
        }
    }
  2. 打開 Extensions/MiddlewareExtension.cs 將 Middleware 引入

    {
        public static IApplicationBuilder ConfigureMiddlewares(this IApplicationBuilder builder)
        {
            // 引入 Middleware
            builder.UseMiddleware<ExampleMiddleware>();
    
            return builder;
        }
    }
  3. 確認 Program.cs 中的 app.ConfigureMiddlewares(); 有沒有被啟用

    ...
    var app = builder.Build();
    
    app.ConfigureMiddlewares();
    ...
  4. 完成

Filter

自行撰寫的 Filter 請放置於 Filters 資料夾中,其中若 Filter 中的建構式包含有依賴注入的部份,Controller 使用時請以 [TypeFilter(typeof(YourFilterName))] 撰寫。

如果需要將資料傳遞到 Controller 中,可以利用 context.HttpContext.Items 當作傳遞方法。

HttpClient

自行撰寫的 HttpClient 請放置於 HttpClients 資料夾中,撰寫完後,請打開 Extensions/HttpClientExtension.cs 檔,增加 serviceCollection.AddHttpClient<YourCustomClient>(); 即可。

參考資料

IDE 設定

基礎建置

Repository 建置與資料庫連線

AutoMapper

Configuration

Docker 相關

驗證與 Swagger 相關

HttpClient 相關

Middleware 相關

Filter 相關

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.