2025年7月10日 星期四

[研究]ASP.NET WebForm 執行過久跳轉 Exception 畫面之處理

[研究]ASP.NET WebForm 執行過久跳轉 Exception 畫面之處理

2025-07-10

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

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

ASP.NET WebForm 同一個 .aspx 網頁,因為計算的東西複雜,在效能好的機器上正常運作,在效能較差虛擬機上,執行一陣子自動跳轉到 Exception 畫面。

ChatGPT 回答的太拉雜囉嗦,整理數次詢問的結果。

全域設定,可改 Web.Config,預設 90秒, 最大值(上限):Int32.MaxValue 秒,2,147,483,647 秒 ≒ 68 年

<configuration>
  <system.web>
    <httpRuntime executionTimeout="300" />
  </system.web>
</configuration>

只改單一網頁,注意,Server.ScriptTimeout  設定超過 executionTimeout 是無用的。

protected void Button1_Click(object sender, EventArgs e)
{
    Server.ScriptTimeout = 300;

    try
    {
        // 假設是複雜計算
        DoHeavyCalculation();
        lblResult.Text = "計算完成。";
    }
    catch (TimeoutException ex)
    {
        lblResult.Text = "計算逾時,請簡化條件或稍後再試。";
        // 可以記錄詳細例外訊息
        LogException(ex);
    }
    catch (Exception ex)
    {
        lblResult.Text = "發生錯誤:" + ex.Message;
        LogException(ex);
    }
}


另外考慮是否因為去 DB 中抓資料時間超過,CommandTimeout 預設 30 秒,下面可以改為 180 秒。

SqlCommand command = new SqlCommand("your SQL here", connection);
command.CommandTimeout = 180; // 改為 3 分鐘
ㄌ

捕捉例外

try
{
    using (SqlConnection connection = new SqlConnection("your connection string"))
    {
        connection.Open();
        SqlCommand command = new SqlCommand("your SQL here", connection);
        command.CommandTimeout = 30;

        using (SqlDataReader reader = command.ExecuteReader())
        {
            // 處理資料
        }
    }
}
catch (SqlException ex)
{
    if (ex.Number == -2) // timeout
    {
        // 處理查詢逾時
        Response.Write("資料庫查詢逾時,請稍後再試。");
    }
    else
    {
        // 處理其他 SQL 錯誤
        Response.Write("資料庫錯誤:" + ex.Message);
    }
}
catch (Exception ex)
{
    // 處理非 SQL 的其他例外
    Response.Write("系統發生錯誤:" + ex.Message);
}

另外也可能是記憶體不足,或 IIS Request Timeout 設定過短 (可在 IIS 裡 Application Pool → Limits → Request Timeout 設定 ),或 Proxy、CDN、、、等因素。

**********

敝人最後是靠改成下面解決問題。

<httpRuntime executionTimeout="300" />

command.CommandTimeout = 300; // 改為 5 分鐘

(完)

相關

沒有留言:

張貼留言