2025年5月6日 星期二

[研究]如何限制 ASP.NET WebForm Web Application 網站的同時連線數 ? 總連線數 ?

[研究]如何限制 ASP.NET WebForm Web Application 網站的同時連線數 ? 總連線數 ?

2025-05-06

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

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

在 ASP.NET WebForms Web Application 網站中,要限制「同時連線數(Concurrent Connections)」或「總連線數(Total Connections)」可以透過以下幾種方式實現:


一、使用 IIS(Internet Information Services)限制

[研究]如何限制 IIS 或 IIS 底下網站的同時連線數 ? 總連線數 ?

https://shaurong.blogspot.com/2025/05/iis-iis.html

注意:此功能可能在 Windows Server 的 Standard / Datacenter 版才完整支援,在 Windows 10/11 或非伺服器版本中可能有內建限制(如 10 個連線限制)。


二、使用 web.config 中的 httpRuntime 元素限制

<configuration>
  <system.web>
    <httpRuntime maxRequestLength="4096" requestQueueLimit="100" />   
  </system.web>
</configuration>

requestQueueLimit:設定在工作執行緒忙碌時,最多排隊多少個請求(超過會返回 503)。

這不直接限制同時連線數,但可以限制高佇列情況的行為。


三、在 Global.asax 中程式碼實作限制(應用程式層級控制)

實作同時處理請求的簡易方式(不建議大規模使用)

private static int _currentRequestCount = 0;
private static int _maxRequestCount = 100;

void Application_BeginRequest(object sender, EventArgs e)
{
    if (Interlocked.Increment(ref _currentRequestCount) > _maxRequestCount)
    {
        Response.StatusCode = 503; // Service Unavailable
        Response.End();
    }
}

void Application_EndRequest(object sender, EventArgs e)
{
    Interlocked.Decrement(ref _currentRequestCount);
}

優點:簡單可控

缺點:不考慮非同步請求、重載和分散式部署下的準確性。


四、總結

方法可限制適用情境備註
IIS Connection Limits同時連線數一般部署簡單有效
web.config httpRuntime佇列長度小型網站間接控制
Global.asax 控制同時請求精細管控可程式化

(完)

相關

[研究]如何限制 IIS 或 IIS 底下網站的同時連線數 ? 總連線數 ?
https://shaurong.blogspot.com/2025/05/iis-iis.html

[研究]如何限制 ASP.NET WebForm Web Application 網站的同時連線數 ? 總連線數 ?
https://shaurong.blogspot.com/2025/05/aspnet-webform-web-application.html


沒有留言:

張貼留言