2025年12月2日 星期二

[研究]ASP.NET Webform 取得 Request Id 或 Response Id 儲存到的 Log Table ?

[研究]ASP.NET Webform 取得 Request Id 或 Response Id 儲存到的 Log Table ?

2025-12-02

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 20.2

********************************************************************************

✅ 一、WebForm 沒有內建 RequestId,需要自行產生

ASP.NET Core 才有內建 HttpContext.TraceIdentifier。

ASP.NET WebForm (.NET Framework) 沒有預設 RequestId,所以我們要 自行產生 GUID 或類似唯一值,並在整個 Request 生命周期保持一致。

最常見方式:

每一個 Request 進入 Pipeline 時產生 RequestId

儲存在 HttpContext.Items 中(僅在該 Request 有效)

Log 時從 HttpContext.Items 取得

✅ 二、在 Global.asax 產生 RequestId(推薦做法)

Global.asax

protected void Application_BeginRequest(object sender, EventArgs e)
{
    string requestId = Guid.NewGuid().ToString();
    HttpContext.Current.Items["RequestId"] = requestId;
}

✅ 三、在任何 .aspx.cs 取得 RequestId

Page_Load / Button_Click / 任何地方

string requestId = HttpContext.Current.Items["RequestId"]?.ToString();

、、、(略)

**********

其實說穿了,ChatGPT 只是讓 table 中每一筆資料有一個唯一的值而已,用 SQL Server 的 識別 IDENTITY(1,1) 即可。而 Request Id 和 Response Id 其實用同一個欄位即可。


(完)


沒有留言:

張貼留言