這份檔案將會說明如何從這個模板中開始新的後端解決方案
- 請先關閉 Visual Studio 後,將資料夾名稱重新命名
- 以 Visual Studio 重新開啟專案,並針對 Api 專案中
ProjectReference
的路徑做修改若找不到此宣告,則可跳過這步驟
- 將 API、Repository 專案名稱重新命名
- 針對專案點選右鍵 -> 同步命名空間
- 修改
build-push-deploy.yml
檔中的DotNet7.Template.Api/Dockerfile
將DotNet7.Template.Api
修改為正確的專案名稱 - 確認各類別與介面的命名空間是否正確
- 若有需要,可以修改
appsettings.Development.json
中Swagger.RoutePrefix
設定,此用途為設定 API 路徑前綴
另外,若 Visual Studio 將檔案儲存成 UTF-8 With BOM 會造成問題,請依據以下步驟設定:
- 安裝
Fix File Encoding
延伸模組 - 打開
工具
>選項
> 左側選單選擇Fix File Encoding
- 在右側
UTF8 without signature files regex
輸入框中輸入\.(.+)$
全部套用 - 按下確定完成
如需使用資料庫,請打開 Extensions/DatabaseExtension.cs
將註解全部打開,並修改 DBContext 名稱為正確的名稱,同時請將資料庫連線字串、資料庫帳號與密碼設定完成,否則專案將無法啟動
Service 與 Repository 的類別與介面需進行綁定,否則 DI 將無法正常注入
- 打開
Extensions/ServiceMapperExtension.cs
,依據範例將類別與介面綁定起來
-
先將 Repository 專案設定為啟動專案
-
使用以下指令將指定資料庫中的資料表進行反向工程,建立出 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
-
打開
Extensions/DatabaseExtension.cs
,將最下方的註解打開,並將 DBContext 修改為正確的類別若有多個 DBContext 也請在這邊一並宣告
-
將 Api 專案設定為啟動專案
- 在
AutoMapperProfiles
資料夾下新增一個 任意名稱的 Profile 類別 - 在類別中宣告需要進行 Mapper 的類別綁定
ASP.Net 取用設定名稱常使用 :
作為階層的分隔,但許多系統並不支援於環境變數名稱中包含 :
字符,因此可以 __
(雙底線) 取代 :
,其內部會自動做轉換。
若需要於正式機器上使用 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";
請參考這篇文章
如果需要將資料傳遞到 Controller 中,可以利用
context.HttpContext.Items
當作傳遞方法。
-
在
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); // 在處理請求「後」要先執行的程式 } } }
-
打開
Extensions/MiddlewareExtension.cs
將 Middleware 引入{ public static IApplicationBuilder ConfigureMiddlewares(this IApplicationBuilder builder) { // 引入 Middleware builder.UseMiddleware<ExampleMiddleware>(); return builder; } }
-
確認
Program.cs
中的app.ConfigureMiddlewares();
有沒有被啟用... var app = builder.Build(); app.ConfigureMiddlewares(); ...
-
完成
自行撰寫的 Filter 請放置於 Filters
資料夾中,其中若 Filter 中的建構式包含有依賴注入的部份,Controller 使用時請以 [TypeFilter(typeof(YourFilterName))]
撰寫。
如果需要將資料傳遞到 Controller 中,可以利用
context.HttpContext.Items
當作傳遞方法。
自行撰寫的 HttpClient 請放置於 HttpClients
資料夾中,撰寫完後,請打開 Extensions/HttpClientExtension.cs
檔,增加 serviceCollection.AddHttpClient<YourCustomClient>();
即可。
- How can I rename a project folder from within Visual Studio?
- Datetime utc issue after migrating to .NET Core 7
- Visual Studio: Add existing folder(s) to project
- ! (null-forgiving) operator (C# reference)
- 在 ASP.NET 核心中啟用跨原始來源要求 (CORS)
- How to enable CORS in ASP.NET Core
- Using the Repository Pattern with the Entity Framework
- Scaffolding (Reverse Engineering)
- Get ConnectionString from appsettings.json
- Setting connection string with username and password in ASP.Core
- [EF Core] 使用.NET Core CLI建立資料庫實體類型
- Creating a Model for an Existing Database in Entity Framework Core
- Pomelo EntityFrameworkCore Mysql - Getting Started
- Configuration in ASP.NET Core
- Non-prefixed environment variables
- ASP.NET Core Configuration values sometimes returns empty in Kubernetes
- ASP.NET Core Environment variable colon in Linux
- [Docker] .NET Core 的 Dockerfile 指令詳解
- dotnet publish
- 使用 dotnet 命令列工具發行 .NET 6 專案
- 教學課程:容器化 .NET 應用程式
- Override ASP.NET Core appsettings key name that as dots with environment variable in a container
- Does Swagger (Asp.Net Core) have a controller description?
- How to add method description in Swagger UI in WebAPI Application
- Swashbuckle.AspNetCore Include Descriptions From XML Comments
- ASP.NET Core 驗證的概觀
- How to set base path property in swagger for .Net Core Web API
- What's the difference between HttpRequest.Path and HttpRequest.PathBase in ASP.NET Core?
- Enabling authentication in swagger
- 在 Swagger UI 加上驗證按鈕,讓 Request Header 傳遞 Authorize Token
- Using Authorization with Swagger in ASP.NET Core
- 是誰在敲打我窗?什麼是 JWT ?
- Write custom ASP.NET Core middleware
- A web app that calls web APIs: Acquire a token for the app
- How to Add a BearerToken to an HttpClient Request
- How to get access token from HttpContext in .Net core 2.0
- Fetch access token from authorization header without bearer prefix
- Why is StringValues used for Request.Query values?
- 在 ASP.NET Core 中使用 IHttpClientFactory 發出 HTTP 要求
- .NET Core 中正確使用 HttpClient 的姿勢
- [C#] Web API - HttpClient 入門
- .net services.AddHttpClient Automatic Access Token Handling
- HTTP 有效內容回應 - 使用 HttpClient 類別提出 HTTP 要求
- ASP.NET Core 中介軟體
- ASP.NET Core 基礎 - Middleware
- Setting middleware for specific controller in ASP.NET Core
- Custom middleware (or authorize) for specific route in ASP .NET Core 3.1 MVC
- Use Middleware for some controllers
- .net-core middleware return blank result
- Write custom ASP.NET Core middleware
- Is it possible to send values to controller from middleware in aspnet core api?
- ASP.NET Core Middleware Passing Parameters to Controllers
- ASP.NET Core 中的篩選條件
- Custom Authorization Attribute in .Net Core 5
- How do you create a custom AuthorizeAttribute in ASP.NET Core?
- ASP.NET Core Web API custom AuthorizeAttribute issue
- How can I use Dependency Injection in a .Net Core ActionFilterAttribute?
- async action filter: Async & AuthorizeAttribute in ASP.NET WEB API
- HttpContext.Items with ASP.NET MVC
- ASP.NET Core 中的存取 HttpContext