Files
xSaherelmWorkspace/Documents/Docs/Developer/Implementing RateLimit Feature 1.html
2026-11-09 15:42:26 +03:30

1566 lines
57 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>گزارش پیاده‌سازی سفارشی RateLimit در ماژول xCommons</title>
<style>
:root {
--bg: #f8fafc;
--card: #ffffff;
--text: #0f172a;
--muted: #475569;
--primary: #0ea5e9;
--primary-dark: #0369a1;
--border: #e2e8f0;
--code-bg: #0f172a;
--code-text: #e2e8f0;
--warning: #f59e0b;
--success: #10b981;
--danger: #ef4444;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
background: var(--bg);
color: var(--text);
font-family: Tahoma, "Segoe UI", Arial, sans-serif;
line-height: 1.9;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 24px;
}
header.hero {
background: linear-gradient(135deg, #0f172a, #0369a1);
color: #fff;
border-radius: 18px;
padding: 32px;
margin-bottom: 24px;
box-shadow: 0 12px 30px rgba(15, 23, 42, 0.18);
}
header.hero h1 {
margin: 0 0 12px;
font-size: 30px;
}
header.hero p {
margin: 0;
color: #e0f2fe;
}
.layout {
display: grid;
grid-template-columns: 300px 1fr;
gap: 24px;
align-items: start;
}
.toc {
position: sticky;
top: 24px;
background: var(--card);
border: 1px solid var(--border);
border-radius: 16px;
padding: 18px;
box-shadow: 0 8px 20px rgba(15, 23, 42, 0.05);
}
.toc h2 {
margin: 0 0 12px;
font-size: 18px;
}
.toc a {
display: block;
color: var(--muted);
text-decoration: none;
padding: 7px 10px;
border-radius: 8px;
font-size: 14px;
}
.toc a:hover {
background: #e0f2fe;
color: var(--primary-dark);
}
.content {
display: flex;
flex-direction: column;
gap: 24px;
}
section.card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 16px;
padding: 24px;
box-shadow: 0 8px 20px rgba(15, 23, 42, 0.05);
}
section.card h2 {
margin-top: 0;
color: var(--primary-dark);
border-bottom: 2px solid #e0f2fe;
padding-bottom: 8px;
}
section.card h3 {
color: #0f172a;
margin-top: 24px;
}
table {
width: 100%;
border-collapse: collapse;
margin: 14px 0;
font-size: 14px;
}
th, td {
border: 1px solid var(--border);
padding: 10px 12px;
vertical-align: top;
}
th {
background: #f1f5f9;
text-align: right;
}
tr:nth-child(even) td {
background: #f8fafc;
}
code.inline {
background: #e2e8f0;
color: #0f172a;
padding: 2px 6px;
border-radius: 5px;
font-family: Consolas, Monaco, monospace;
direction: ltr;
display: inline-block;
}
pre {
background: var(--code-bg);
color: var(--code-text);
padding: 18px;
border-radius: 12px;
overflow-x: auto;
direction: ltr;
text-align: left;
font-family: Consolas, Monaco, "Courier New", monospace;
font-size: 13px;
line-height: 1.65;
border: 1px solid #1e293b;
}
pre code {
white-space: pre;
}
.note {
border-right: 5px solid var(--warning);
background: #fffbeb;
padding: 14px 16px;
border-radius: 10px;
margin: 14px 0;
}
.success {
border-right-color: var(--success);
background: #ecfdf5;
}
.danger {
border-right-color: var(--danger);
background: #fef2f2;
}
.badge {
display: inline-block;
background: #e0f2fe;
color: #0369a1;
padding: 3px 9px;
border-radius: 999px;
font-size: 12px;
margin-left: 6px;
}
.steps li {
margin-bottom: 10px;
}
.flow {
background: #f1f5f9;
border: 1px dashed #94a3b8;
padding: 16px;
border-radius: 12px;
font-family: Consolas, Monaco, monospace;
direction: ltr;
text-align: left;
overflow-x: auto;
}
@media (max-width: 900px) {
.layout {
grid-template-columns: 1fr;
}
.toc {
position: static;
}
}
</style>
</head>
<body>
<div class="container">
<header class="hero">
<h1>گزارش پیاده‌سازی سفارشی RateLimit در ماژول xCommons</h1>
<p>
بررسی کامل سورس ارائه‌شده، استخراج الگوهای کدنویسی، طراحی و پیاده‌سازی گام‌به‌گام
RateLimit سفارشی با <code class="inline">IMemoryCache</code> برای ASP.NET Core 3.1
</p>
</header>
<div class="layout">
<aside class="toc">
<h2>فهرست مطالب</h2>
<a href="#summary">خلاصه مدیریتی</a>
<a href="#source-review">بررسی کامل سورس ارائه‌شده</a>
<a href="#patterns">الگوهای کدنویسی استخراج‌شده</a>
<a href="#design">طراحی RateLimit سفارشی</a>
<a href="#steps">پیاده‌سازی گام‌به‌گام</a>
<a href="#appsettings">تنظیمات appsettings.json</a>
<a href="#constants">Constants و Configuration</a>
<a href="#models">Models و Interface</a>
<a href="#provider">Provider با IMemoryCache</a>
<a href="#attribute">Attribute برای Controller/Action</a>
<a href="#middleware">Middleware سراسری</a>
<a href="#di">ثبت DI و Middleware</a>
<a href="#usage">روش‌های استفاده</a>
<a href="#notes">نکات مهم و محدودیت‌ها</a>
</aside>
<main class="content">
<section class="card" id="summary">
<h2>۱. خلاصه مدیریتی</h2>
<p>
در ASP.NET Core 3.1 قابلیت Rate Limiting توکار با
<code class="inline">AddRateLimiter</code> و
<code class="inline">UseRateLimiter</code> وجود ندارد؛ این قابلیت از .NET 7 به بعد اضافه شده است.
بنابراین برای این ماژول، یک پیاده‌سازی سفارشی مطابق با سبک کدنویسی موجود در
<strong>xCommons</strong> طراحی شده است.
</p>
<p>
راهکار پیشنهادی شامل این اجزا است:
</p>
<ul>
<li>یک <strong>Provider</strong> مبتنی بر <code class="inline">IMemoryCache</code> برای نگهداری شمارنده درخواست‌ها.</li>
<li>یک <strong>Attribute</strong> برای اعمال RateLimit روی Controller یا Action.</li>
<li>یک <strong>Middleware</strong> برای اعمال RateLimit سراسری بر اساس قوانین تنظیمات.</li>
<li>استفاده دستی از Provider در Controller یا Service برای سناریوهای خاص.</li>
<li>پشتیبانی از کلید محدودسازی بر اساس IP، ClientId، User و Route.</li>
</ul>
<div class="note success">
<strong>نتیجه:</strong> پیاده‌سازی زیر با الگوی
<code class="inline">partial class</code>،
<code class="inline">extension method</code>،
<code class="inline">XException.InvalidArgs.Throw()</code>،
<code class="inline">IsNull/IsNullOrEmpty/HasChild/ToNormalString</code>
و ساختار Namespaceهای موجود هماهنگ است.
</div>
</section>
<section class="card" id="source-review">
<h2>۲. بررسی کامل سورس ارائه‌شده</h2>
<p>
سورس ارائه‌شده شامل زیرساخت‌های مشترک ماژول <strong>xCommons</strong> است. این ماژول
نقش پایه مشترک بین پروژه‌ها را دارد و شامل Attributeها، Authorization، Configuration،
Constants، Controllerهای پایه، DI، Extensionها، Filterها، Helperها، Interfaceها،
Modelها و Providerها است.
</p>
<h3>۲.۱. نقشه فایل‌ها و مسئولیت‌ها</h3>
<table>
<thead>
<tr>
<th>گروه</th>
<th>فایل‌های کلیدی</th>
<th>مسئولیت</th>
</tr>
</thead>
<tbody>
<tr>
<td>Attributes</td>
<td><code class="inline">RequireXPoweredAttribute.cs</code></td>
<td>فیلتر احراز هدر <code class="inline">X-PoweredBy</code> با پشتیبانی از AllowAnonymous.</td>
</tr>
<tr>
<td>Authorization</td>
<td><code class="inline">RequiredRolesHandler.cs</code>، <code class="inline">RequiredRolesRequirement.cs</code></td>
<td>پیاده‌سازی Authorization مبتنی بر Role Claim.</td>
</tr>
<tr>
<td>Configurations</td>
<td><code class="inline">XAppConfiguration.cs</code>، <code class="inline">XSwaggerConfiguration.cs</code>، <code class="inline">XFileTypeDetectorConfiguration.cs</code></td>
<td>مدل‌های تنظیمات برنامه و سرویس‌های جانبی.</td>
</tr>
<tr>
<td>Constants</td>
<td><code class="inline">ConfigurationNodeNames.cs</code>، <code class="inline">XAuthorization.cs</code>، <code class="inline">XCustomClaims.cs</code>، <code class="inline">XPolicy.cs</code></td>
<td>ثابت‌های نام Node تنظیمات، هدرها، Claimها و Policyها.</td>
</tr>
<tr>
<td>Controllers</td>
<td><code class="inline">XBaseController.cs</code>، <code class="inline">XBaseApiController.cs</code>، <code class="inline">XBaseApiV1Controller.cs</code></td>
<td>Controllerهای پایه با Route، Produces، RequireXPowered و ابزارهای خطا.</td>
</tr>
<tr>
<td>DI</td>
<td><code class="inline">XDIHelperExtension.cs</code>، <code class="inline">DIExtensions.cs</code></td>
<td>ثبت سرویس‌های ماژول، Swagger، CORS، Versioning و FileTypeDetector.</td>
</tr>
<tr>
<td>Extensions</td>
<td><code class="inline">CommonExtensions.cs</code>، <code class="inline">IConfigurationExtensions.cs</code>، <code class="inline">XHttpExtensions.cs</code>، <code class="inline">FilterExtensions.cs</code></td>
<td>Extensionهای عمومی، خواندن تنظیمات، HTTP، Filter و ... .</td>
</tr>
<tr>
<td>Filters</td>
<td><code class="inline">RequireXPoweredOperationFilter.cs</code>، <code class="inline">SwaggerDefaultValuesOperationFilter.cs</code></td>
<td>OperationFilterهای Swagger.</td>
</tr>
<tr>
<td>Helpers</td>
<td><code class="inline">XFileHelper.cs</code>، <code class="inline">XReflectionHelper.cs</code>، <code class="inline">XOsHelper.cs</code>، <code class="inline">XNetworkHelper.cs</code></td>
<td>ابزارهای فایل، Reflection، OS و Network.</td>
</tr>
<tr>
<td>Interfaces</td>
<td><code class="inline">IXCipher.cs</code>، <code class="inline">IXFileTypeDetector.cs</code></td>
<td>قراردادهای سرویس‌های رمزنگاری و تشخیص نوع فایل.</td>
</tr>
<tr>
<td>Models</td>
<td><code class="inline">XFileTypeInfo.cs</code>، <code class="inline">XFileTypeDetectionResult.cs</code>، <code class="inline">XLoggerModel.cs</code></td>
<td>مدل‌های داده مشترک.</td>
</tr>
<tr>
<td>Providers</td>
<td><code class="inline">XFileTypeDetector.cs</code>، <code class="inline">XCipher.cs</code>، <code class="inline">XValidationProvider.cs</code>، <code class="inline">XBackgroundService.cs</code></td>
<td>پیاده‌سازی سرویس‌ها و BackgroundServiceهای پایه.</td>
</tr>
</tbody>
</table>
<h3>۲.۲. نکات معماری استخراج‌شده</h3>
<ul>
<li>استفاده گسترده از <code class="inline">partial class</code> و <code class="inline">partial struct</code> برای توسعه‌پذیری.</li>
<li>استفاده از <code class="inline">extension method</code> برای عملیات عمومی مانند Null Check، JSON، String، Configuration و HTTP.</li>
<li>تنظیمات به‌صورت POCO تعریف می‌شوند و با Extensionهای <code class="inline">IConfiguration</code> خوانده می‌شوند.</li>
<li>خطاها با <code class="inline">XException</code> و متدهای الحاقی <code class="inline">Throw()</code> مدیریت می‌شوند.</li>
<li>اعتبارسنجی ورودی‌ها با <code class="inline">XValidationProvider</code> انجام می‌شود.</li>
<li>ثبت سرویس‌ها با Extensionهای <code class="inline">IServiceCollection</code> و نام‌گذاری <code class="inline">AddX...</code> انجام می‌شود.</li>
<li>فیلترها و Attributeها از <code class="inline">RequestServices</code> برای دسترسی به سرویس‌ها استفاده می‌کنند.</li>
<li>نام‌گذاری‌ها با پیشوند <code class="inline">X</code> و Namespaceهای <code class="inline">xCommons.*</code> ادامه یافته است.</li>
</ul>
<h3>۲.۳. نکات قابل توجه در سورس فعلی</h3>
<ul>
<li>
<code class="inline">XMiddlewareExtensions.cs</code> در حال حاضر خالی و غیر partial است؛ برای افزودن
<code class="inline">UseXRateLimit</code> باید به <code class="inline">public static partial class</code> تغییر کند.
</li>
<li>
<code class="inline">XHttpContextExtensions.cs</code> از قبل partial است؛ بنابراین افزودن Extensionهای
RateLimit در همان کلاس امکان‌پذیر است.
</li>
<li>
<code class="inline">IConfigurationExtensions.cs</code> از قبل partial است؛ افزودن
<code class="inline">GetXRateLimitConfiguration</code> در فایل جداگانه امکان‌پذیر است.
</li>
<li>
<code class="inline">DIExtensions.cs</code> از قبل partial است؛ افزودن
<code class="inline">AddXRateLimit</code> در همان کلاس انجام می‌شود.
</li>
<li>
برای سازگاری با ASP.NET Core 3.1 در کد جدید از Target-typed <code class="inline">new()</code>
استفاده نشده و در صورت نیاز از نوع صریح استفاده شده است.
</li>
</ul>
</section>
<section class="card" id="patterns">
<h2>۳. الگوهای کدنویسی مورد استفاده در پیاده‌سازی</h2>
<table>
<thead>
<tr>
<th>الگو</th>
<th>نمونه در کد جدید</th>
</tr>
</thead>
<tbody>
<tr>
<td>Partial Class/Struct</td>
<td><code class="inline">public partial class XRateLimitProvider</code></td>
</tr>
<tr>
<td>Extension Method</td>
<td><code class="inline">GetXRateLimitKey(this HttpContext ...)</code></td>
</tr>
<tr>
<td>DI Extension</td>
<td><code class="inline">AddXRateLimit(this IServiceCollection ...)</code></td>
</tr>
<tr>
<td>Middleware Extension</td>
<td><code class="inline">UseXRateLimit(this IApplicationBuilder ...)</code></td>
</tr>
<tr>
<td>Null-safe Helperها</td>
<td><code class="inline">IsNull()</code>، <code class="inline">IsNullOrEmpty()</code>، <code class="inline">ToNormalString()</code></td>
</tr>
<tr>
<td>خطای استاندارد</td>
<td><code class="inline">XException.InvalidArgs.Throw()</code></td>
</tr>
<tr>
<td>تنظیمات POCO</td>
<td><code class="inline">XRateLimitConfiguration</code>، <code class="inline">XRateLimitRule</code></td>
</tr>
</tbody>
</table>
</section>
<section class="card" id="design">
<h2>۴. طراحی RateLimit سفارشی</h2>
<p>جریان کلی درخواست به شکل زیر است:</p>
<div class="flow">
Request
|
v
[UseRouting]
|
v
[UseAuthentication] (در صورت استفاده از KeyMode = User)
|
v
[UseXRateLimit] ---> XRateLimitMiddleware
| |
| +--> XRateLimitConfiguration.GetMatchingRule(path)
| +--> HttpContext.GetXRateLimitKey(rule.KeyMode)
| +--> IXRateLimitProvider.TryConsume(key, rule)
| |
| +--> if !IsAllowed => 429 + Retry-After
v
[UseAuthorization]
|
v
[UseEndpoints] ---> MVC Action
|
+--> [XRateLimit] Attribute (IActionFilter)
+--> IXRateLimitProvider.TryConsume(...)
</div>
<h3>۴.۱. اجزای طراحی‌شده</h3>
<ul>
<li><strong>XRateLimit</strong>: ثابت‌های Cache Key، نام هدرها و کلید Item.</li>
<li><strong>XRateLimitKeyMode</strong>: حالت انتخاب کلید شامل IP، ClientId، User، Route و Custom.</li>
<li><strong>XRateLimitRule</strong>: قانون محدودسازی برای یک PathPrefix مشخص.</li>
<li><strong>XRateLimitConfiguration</strong>: تنظیمات کلی و لیست قوانین.</li>
<li><strong>XRateLimitResult</strong>: نتیجه بررسی شامل Allow/Deny، Remaining، RetryAfter و ResetOn.</li>
<li><strong>XRateLimitCounter</strong>: شمارنده ذخیره‌شده در IMemoryCache.</li>
<li><strong>IXRateLimitProvider</strong>: قرارداد مصرف RateLimit.</li>
<li><strong>XRateLimitProvider</strong>: پیاده‌سازی مبتنی بر IMemoryCache و lock.</li>
<li><strong>XRateLimitAttribute</strong>: اعمال RateLimit روی Action/Controller.</li>
<li><strong>XRateLimitMiddleware</strong>: اعمال RateLimit سراسری بر اساس قوانین.</li>
</ul>
</section>
<section class="card" id="steps">
<h2>۵. پیاده‌سازی گام‌به‌گام</h2>
<ol class="steps">
<li>افزودن تنظیمات <code class="inline">XRateLimit</code> به <code class="inline">appsettings.json</code>.</li>
<li>افزودن ثابت‌های جدید به <code class="inline">Constants</code> و <code class="inline">ConfigurationNodeNames</code>.</li>
<li>ایجاد مدل‌های تنظیمات، نتیجه و شمارنده.</li>
<li>ایجاد Interface برای Provider.</li>
<li>پیاده‌سازی Provider با <code class="inline">IMemoryCache</code>.</li>
<li>افزودن Extension برای استخراج کلید RateLimit از <code class="inline">HttpContext</code>.</li>
<li>ایجاد Attribute برای Controller/Action.</li>
<li>ایجاد Middleware سراسری.</li>
<li>افزودن Extension خواندن تنظیمات و ثبت DI.</li>
<li>فعال‌سازی Middleware در <code class="inline">Startup.cs</code> و استفاده در Controller.</li>
</ol>
</section>
<section class="card" id="appsettings">
<h2>۶. تنظیمات appsettings.json</h2>
<p>
نمونه تنظیمات زیر را به فایل <code class="inline">appsettings.json</code> اضافه کنید.
اگر <code class="inline">ApplyToAllRoutes</code> برابر <code class="inline">true</code> باشد،
برای همه Routeها از مقدار Default استفاده می‌شود. در غیر این صورت فقط Rules منطبق اعمال می‌شوند.
</p>
<pre><code>{
"XRateLimit": {
"Enabled": true,
"StatusCode": 429,
"DefaultLimit": 60,
"DefaultPeriodSeconds": 60,
"DefaultKeyMode": "Ip",
"ApplyToAllRoutes": false,
"Rules": [
{
"Name": "AuthEndpoints",
"PathPrefix": "/api/v1/auth",
"Limit": 5,
"PeriodSeconds": 60,
"KeyMode": "Ip",
"Enabled": true
},
{
"Name": "PublicEndpoints",
"PathPrefix": "/api/v1/public",
"Limit": 30,
"PeriodSeconds": 60,
"KeyMode": "ClientId",
"Enabled": true
}
]
}
}</code></pre>
</section>
<section class="card" id="constants">
<h2>۷. Constants و Configuration</h2>
<h3>۷.۱. فایل جدید: Constants/XRateLimit.cs</h3>
<pre><code>namespace xCommons.Constants
{
public partial struct XRateLimit
{
public const string CacheKeyPrefix = "xratelimit";
public const string ClientIdHeader = "X-ClientId";
public const string LimitHeader = "X-RateLimit-Limit";
public const string RemainingHeader = "X-RateLimit-Remaining";
public const string ResetHeader = "X-RateLimit-Reset";
public const string RetryAfterHeader = "Retry-After";
public const string AppliedItemKey = "X-RateLimit-Applied";
}
}</code></pre>
<h3>۷.۲. فایل جدید: Constants/XRateLimitKeyMode.cs</h3>
<pre><code>using xExceptions.Attributes;
namespace xCommons.Constants
{
public enum XRateLimitKeyMode
{
[StringValue("Ip")]
Ip = 0,
[StringValue("ClientId")]
ClientId = 1,
[StringValue("User")]
User = 2,
[StringValue("Route")]
Route = 3,
[StringValue("Custom")]
Custom = 4
}
}</code></pre>
<h3>۷.۳. تغییر در Constants/ConfigurationNodeNames.cs</h3>
<p>یک ثابت برای نام Node تنظیمات RateLimit اضافه کنید:</p>
<pre><code>namespace xCommons.Constants
{
public partial struct ConfigurationNodeNames
{
public const string CERTIFICATES_NODE = "Certificates";
public const string SWAGGER_NODE = "SwaggerConfiguration";
public const string FILE_TYPE_DETECTOR_NODE = "FileTypeDetectorConfiguration";
public const string MESSAGE_RESOURCE_TITLES_NODE = "MessageResourceTitles";
// New
public const string RATE_LIMIT_NODE = "XRateLimit";
}
}</code></pre>
<h3>۷.۴. فایل جدید: Configurations/XRateLimitConfiguration.cs</h3>
<pre><code>using System;
using System.Linq;
using System.Collections.Generic;
using xCommons.Constants;
using xCommons.Extensions;
namespace xCommons.Configurations
{
public partial class XRateLimitConfiguration
{
public bool Enabled { get; set; } = false;
public int StatusCode { get; set; } = 429;
public int DefaultLimit { get; set; } = 60;
public int DefaultPeriodSeconds { get; set; } = 60;
public XRateLimitKeyMode DefaultKeyMode { get; set; } = XRateLimitKeyMode.Ip;
public bool ApplyToAllRoutes { get; set; } = false;
public ICollection&lt;XRateLimitRule&gt; Rules { get; set; } = new List&lt;XRateLimitRule&gt;();
public XRateLimitRule GetMatchingRule(string path)
{
//
if (!Enabled)
{
return null;
}
//
var normalizedPath = path.IsNullOrEmpty()
? "/"
: path.ToNormalString();
//
var rule = Rules.IsNull()
? null
: Rules
.Where(r =>
!r.IsNull() &&
r.Enabled &&
!r.PathPrefix.IsNullOrEmpty() &&
normalizedPath.StartsWith(r.PathPrefix.ToNormalString()))
.OrderByDescending(r => r.PathPrefix.Length)
.FirstOrDefault();
//
if (!rule.IsNull())
{
return rule;
}
//
if (ApplyToAllRoutes)
{
return new XRateLimitRule
{
Name = "Default",
PathPrefix = "/",
Limit = DefaultLimit,
PeriodSeconds = DefaultPeriodSeconds,
KeyMode = DefaultKeyMode,
Enabled = true
};
}
//
return null;
}
}
public partial class XRateLimitRule
{
public string Name { get; set; } = string.Empty;
public string PathPrefix { get; set; } = "/";
public int Limit { get; set; } = 60;
public int PeriodSeconds { get; set; } = 60;
public XRateLimitKeyMode KeyMode { get; set; } = XRateLimitKeyMode.Ip;
public bool Enabled { get; set; } = true;
}
}</code></pre>
</section>
<section class="card" id="models">
<h2>۸. Models و Interface</h2>
<h3>۸.۱. فایل جدید: Models/XRateLimitResult.cs</h3>
<pre><code>using System;
namespace xCommons.Models
{
public partial class XRateLimitResult
{
public bool IsAllowed { get; set; }
public string Key { get; set; }
public int Limit { get; set; }
public int Remaining { get; set; }
public int RetryAfterSeconds { get; set; }
public DateTimeOffset ResetOn { get; set; }
}
}</code></pre>
<h3>۸.۲. فایل جدید: Models/XRateLimitCounter.cs</h3>
<pre><code>using System;
namespace xCommons.Models
{
public partial class XRateLimitCounter
{
public int Count { get; set; }
public int Limit { get; set; }
public DateTimeOffset ResetOn { get; set; }
}
}</code></pre>
<h3>۸.۳. فایل جدید: Interfaces/IXRateLimitProvider.cs</h3>
<pre><code>using xCommons.Models;
using xCommons.Configurations;
namespace xCommons.Interfaces
{
public interface IXRateLimitProvider
{
bool IsEnabled { get; }
XRateLimitResult TryConsume(
string key,
int limit,
int periodSeconds
);
XRateLimitResult TryConsume(
string key,
XRateLimitRule rule
);
}
}</code></pre>
</section>
<section class="card" id="provider">
<h2>۹. Provider مبتنی بر IMemoryCache</h2>
<p>
این کلاس شمارنده‌ها را در <code class="inline">IMemoryCache</code> نگهداری می‌کند.
برای جلوگیری از Race Condition از یک <code class="inline">lock</code> به ازای هر Cache Key
استفاده شده است. همچنین هنگام Evict شدن Entry، قفل مربوطه نیز پاک می‌شود.
</p>
<pre><code>using System;
using System.Linq;
using System.Threading;
using xCommons.Models;
using xCommons.Extensions;
using xCommons.Interfaces;
using xCommons.Constants;
using System.Threading.Tasks;
using xCommons.Configurations;
using xExceptions.Constants;
using System.Collections.Generic;
using System.Collections.Concurrent;
using Microsoft.Extensions.Caching.Memory;
namespace xCommons.Providers
{
public partial class XRateLimitProvider : IXRateLimitProvider
{
private readonly IMemoryCache cache;
private readonly XRateLimitConfiguration configuration;
private readonly ConcurrentDictionary&lt;string, object&gt; syncRoots =
new ConcurrentDictionary&lt;string, object&gt;();
public XRateLimitProvider(
IMemoryCache cache,
XRateLimitConfiguration configuration
)
{
this.cache = cache;
this.configuration = configuration;
}
public bool IsEnabled
{
get
{
return !configuration.IsNull() && configuration.Enabled;
}
}
public XRateLimitResult TryConsume(
string key,
XRateLimitRule rule
)
{
//
if (rule.IsNull())
{
XException.InvalidArgs.Throw();
}
//
return TryConsume(
key: key,
limit: rule.Limit,
periodSeconds: rule.PeriodSeconds
);
}
public XRateLimitResult TryConsume(
string key,
int limit,
int periodSeconds
)
{
//
if (limit &lt;= 0 || periodSeconds &lt;= 0)
{
XException.InvalidArgs.Throw();
}
//
var normalizedKey = BuildCacheKey(key);
var now = DateTimeOffset.UtcNow;
//
if (!IsEnabled)
{
return new XRateLimitResult
{
IsAllowed = true,
Key = normalizedKey,
Limit = limit,
Remaining = limit,
RetryAfterSeconds = 0,
ResetOn = now.AddSeconds(periodSeconds)
};
}
//
var syncRoot = syncRoots.GetOrAdd(
key: normalizedKey,
valueFactory: _ =&gt; new object()
);
//
lock (syncRoot)
{
//
var counter = cache.Get&lt;XRateLimitCounter&gt;(normalizedKey);
if (counter.IsNull() || counter.ResetOn &lt;= now)
{
counter = new XRateLimitCounter
{
Count = 0,
Limit = limit,
ResetOn = now.AddSeconds(periodSeconds)
};
}
//
counter.Count++;
counter.Limit = limit;
//
var remaining = Math.Max(0, limit - counter.Count);
var isAllowed = counter.Count &lt;= limit;
var retryAfter = isAllowed
? 0
: (int)Math.Ceiling((counter.ResetOn - now).TotalSeconds);
//
var options = new MemoryCacheEntryOptions
{
AbsoluteExpiration = counter.ResetOn
};
//
options.RegisterPostEvictionCallback((cacheKey, value, reason, state) =&gt;
{
syncRoots.TryRemove(cacheKey.ToString(), out _);
});
//
cache.Set(normalizedKey, counter, options);
//
return new XRateLimitResult
{
IsAllowed = isAllowed,
Key = normalizedKey,
Limit = limit,
Remaining = remaining,
RetryAfterSeconds = retryAfter,
ResetOn = counter.ResetOn
};
}
}
private static string BuildCacheKey(string key)
{
//
var normalized = key.IsNullOrEmpty()
? "anonymous"
: key.ToNormalString();
//
return string.Format(
"{0}:{1}",
XRateLimit.CacheKeyPrefix,
normalized
);
}
}
}</code></pre>
</section>
<section class="card" id="attribute">
<h2>۱۰. Attribute برای Controller/Action</h2>
<p>
این Attribute از نوع <code class="inline">IActionFilter</code> است و سرویس‌ها را از
<code class="inline">RequestServices</code> دریافت می‌کند. اگر هم Attribute و هم Middleware
فعال باشند، Middleware به‌صورت خودکار وجود Attribute روی Endpoint را تشخیص داده و از
اعمال دوباره صرف‌نظر می‌کند.
</p>
<pre><code>using System;
using xCommons.Models;
using xCommons.Extensions;
using xCommons.Interfaces;
using xCommons.Constants;
using xCommons.Configurations;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
namespace xCommons.Attributes
{
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Method,
AllowMultiple = false,
Inherited = true
)]
public partial class XRateLimitAttribute : Attribute, IActionFilter, IOrderedFilter
{
public int Limit { get; set; } = 0;
public int PeriodSeconds { get; set; } = 0;
public XRateLimitKeyMode KeyMode { get; set; } = XRateLimitKeyMode.Ip;
public string KeyPrefix { get; set; } = null;
public int Order { get; set; } = -1000;
public void OnActionExecuting(ActionExecutingContext context)
{
//
var provider = context.HttpContext.RequestServices
.GetService&lt;IXRateLimitProvider&gt;();
var configuration = context.HttpContext.RequestServices
.GetService&lt;XRateLimitConfiguration&gt;();
//
if (provider.IsNull() ||
configuration.IsNull() ||
!provider.IsEnabled)
{
return;
}
//
var limit = Limit &gt; 0
? Limit
: configuration.DefaultLimit;
var periodSeconds = PeriodSeconds &gt; 0
? PeriodSeconds
: configuration.DefaultPeriodSeconds;
//
var key = context.HttpContext.GetXRateLimitKey(KeyMode);
if (!KeyPrefix.IsNullOrEmpty())
{
key = string.Format("{0}:{1}", KeyPrefix, key);
}
//
var result = provider.TryConsume(
key: key,
limit: limit,
periodSeconds: periodSeconds
);
//
context.HttpContext.Items[XRateLimit.AppliedItemKey] = true;
WriteHeaders(context.HttpContext, result);
//
if (!result.IsAllowed)
{
context.Result = new ObjectResult(new
{
message = "Too many requests. Please try again later.",
retryAfter = result.RetryAfterSeconds,
resetOn = result.ResetOn
})
{
StatusCode = configuration.StatusCode
};
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
private static void WriteHeaders(
HttpContext context,
XRateLimitResult result
)
{
//
context.Response.Headers[XRateLimit.LimitHeader] =
result.Limit.ToString();
context.Response.Headers[XRateLimit.RemainingHeader] =
result.Remaining.ToString();
context.Response.Headers[XRateLimit.ResetHeader] =
result.ResetOn.ToUnixTimeSeconds().ToString();
//
if (!result.IsAllowed)
{
context.Response.Headers[XRateLimit.RetryAfterHeader] =
result.RetryAfterSeconds.ToString();
}
}
}
}</code></pre>
<h3>۱۰.۱. Extension استخراج کلید RateLimit</h3>
<p>فایل جدید: Extensions/XRateLimitHttpContextExtensions.cs</p>
<pre><code>using System;
using System.Linq;
using xCommons.Constants;
using xCommons.Extensions;
using Microsoft.AspNetCore.Http;
namespace xCommons.Extensions
{
public static partial class XHttpContextExtensions
{
public static string GetXRateLimitKey(
this HttpContext source,
XRateLimitKeyMode keyMode
)
{
//
if (source.IsNull())
{
return "unknown";
}
//
switch (keyMode)
{
case XRateLimitKeyMode.ClientId:
{
var clientId = source.Request.Headers[XRateLimit.ClientIdHeader].ToString();
return clientId.IsNullOrEmpty()
? "anonymous"
: clientId.ToNormalString();
}
case XRateLimitKeyMode.User:
{
var userId = source.User?.FindFirst(XCustomClaims.UserId)?.Value;
if (userId.IsNullOrEmpty())
{
userId = source.User?.Identity?.Name;
}
return userId.IsNullOrEmpty()
? "anonymous"
: userId.ToNormalString();
}
case XRateLimitKeyMode.Route:
{
return string.Format(
"{0}:{1}",
source.Request.Method,
source.Request.Path
).ToNormalString();
}
case XRateLimitKeyMode.Custom:
{
return "custom";
}
case XRateLimitKeyMode.Ip:
default:
{
return source.Connection.RemoteIpAddress
.IsNull()
? "unknown"
: source.Connection.RemoteIpAddress
.ToString()
.ToNormalString();
}
}
}
}
}</code></pre>
</section>
<section class="card" id="middleware">
<h2>۱۱. Middleware سراسری</h2>
<p>
این Middleware باید بعد از <code class="inline">UseRouting</code> و در صورت استفاده از
<code class="inline">KeyMode = User</code> بعد از <code class="inline">UseAuthentication</code>
و قبل از <code class="inline">UseAuthorization</code> ثبت شود.
</p>
<pre><code>using System;
using System.Net;
using System.Linq;
using xCommons.Models;
using xCommons.Attributes;
using xCommons.Extensions;
using xCommons.Interfaces;
using xCommons.Constants;
using System.Threading.Tasks;
using xCommons.Configurations;
using Microsoft.AspNetCore.Http;
namespace xCommons.Middlewares
{
public partial class XRateLimitMiddleware
{
private readonly RequestDelegate next;
private readonly IXRateLimitProvider provider;
private readonly XRateLimitConfiguration configuration;
public XRateLimitMiddleware(
RequestDelegate next,
IXRateLimitProvider provider,
XRateLimitConfiguration configuration
)
{
this.next = next;
this.provider = provider;
this.configuration = configuration;
}
public async Task InvokeAsync(HttpContext context)
{
//
if (!provider.IsEnabled)
{
await next(context);
return;
}
//
var endpoint = context.GetEndpoint();
if (!endpoint.IsNull() &&
!endpoint.Metadata
.GetMetadata&lt;XRateLimitAttribute&gt;()
.IsNull())
{
await next(context);
return;
}
//
var rule = configuration.GetMatchingRule(context.Request.Path);
if (rule.IsNull())
{
await next(context);
return;
}
//
var key = context.GetXRateLimitKey(rule.KeyMode);
var result = provider.TryConsume(key, rule);
//
WriteHeaders(context, result);
//
if (!result.IsAllowed)
{
await context.WriteResponseAsJsonAsync(
status: (HttpStatusCode)configuration.StatusCode,
data: new
{
message = "Too many requests. Please try again later.",
retryAfter = result.RetryAfterSeconds,
resetOn = result.ResetOn
}
);
return;
}
//
await next(context);
}
private static void WriteHeaders(
HttpContext context,
XRateLimitResult result
)
{
//
context.Response.Headers[XRateLimit.LimitHeader] =
result.Limit.ToString();
context.Response.Headers[XRateLimit.RemainingHeader] =
result.Remaining.ToString();
context.Response.Headers[XRateLimit.ResetHeader] =
result.ResetOn.ToUnixTimeSeconds().ToString();
//
if (!result.IsAllowed)
{
context.Response.Headers[XRateLimit.RetryAfterHeader] =
result.RetryAfterSeconds.ToString();
}
}
}
}</code></pre>
</section>
<section class="card" id="di">
<h2>۱۲. ثبت DI و Middleware</h2>
<h3>۱۲.۱. افزودن Extension خواندن تنظیمات</h3>
<p>فایل جدید: Extensions/IConfigurationExtensions.XRateLimit.cs</p>
<pre><code>using System.Collections.Generic;
using xCommons.Constants;
using xCommons.Extensions;
using xCommons.Configurations;
using Microsoft.Extensions.Configuration;
namespace xCommons.Extensions
{
public static partial class IConfigurationExtensions
{
public static XRateLimitConfiguration GetXRateLimitConfiguration(
this IConfiguration source
)
{
//
var section = source
.GetSection(ConfigurationNodeNames.RATE_LIMIT_NODE);
//
var result = section.Get&lt;XRateLimitConfiguration&gt;();
if (result.IsNull())
{
result = new XRateLimitConfiguration();
}
//
if (result.Rules.IsNull())
{
result.Rules = new List&lt;XRateLimitRule&gt;();
}
//
return result;
}
}
}</code></pre>
<h3>۱۲.۲. افزودن Extension ثبت DI</h3>
<p>فایل جدید: Extensions/DIExtensions.XRateLimit.cs</p>
<pre><code>using xCommons.Interfaces;
using xCommons.Extensions;
using xCommons.Providers;
using xCommons.Configurations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace xCommons.Extensions
{
public static partial class DIExtensions
{
public static void AddXRateLimit(
this IServiceCollection source,
IConfiguration configuration
)
{
//
var config = configuration.GetXRateLimitConfiguration();
source.AddXRateLimit(config);
}
public static void AddXRateLimit(
this IServiceCollection source,
XRateLimitConfiguration configuration
)
{
//
if (configuration.IsNull())
{
configuration = new XRateLimitConfiguration();
}
//
source.AddMemoryCache();
source.AddSingleton(configuration);
source.AddSingleton&lt;IXRateLimitProvider, XRateLimitProvider&gt;();
}
}
}</code></pre>
<h3>۱۲.۳. تغییر در Extensions/XMiddlewareExtensions.cs</h3>
<p>
این فایل باید به <code class="inline">partial</code> تبدیل شود و متد
<code class="inline">UseXRateLimit</code> به آن اضافه شود:
</p>
<pre><code>using xCommons.Middlewares;
using Microsoft.AspNetCore.Builder;
namespace xCommons.Extensions
{
public static partial class XMiddlewareExtensions
{
public static void UseXRateLimit(
this IApplicationBuilder source
)
{
//
source.UseMiddleware&lt;XRateLimitMiddleware&gt;();
}
}
}</code></pre>
</section>
<section class="card" id="usage">
<h2>۱۳. روش‌های استفاده</h2>
<h3>۱۳.۱. روش اول: استفاده از Attribute روی Action</h3>
<pre><code>using xCommons.Constants;
using xCommons.Attributes;
using xCommons.Controllers;
using Microsoft.AspNetCore.Mvc;
namespace xSaherelm.Api.Controllers
{
public class AuthController : XBaseApiV1Controller
{
public AuthController(
ILogger&lt;AuthController&gt; logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
validationProvider
)
{
}
[HttpPost]
[Route("Login")]
[XRateLimit(
Limit = 5,
PeriodSeconds = 60,
KeyMode = XRateLimitKeyMode.Ip,
KeyPrefix = "auth-login"
)]
public IActionResult Login()
{
return Ok("Login endpoint is protected by RateLimit.");
}
}
}</code></pre>
<h3>۱۳.۲. روش دوم: استفاده از Attribute روی Controller</h3>
<pre><code>[XRateLimit(
Limit = 30,
PeriodSeconds = 60,
KeyMode = XRateLimitKeyMode.ClientId
)]
public class PublicController : XBaseApiV1Controller
{
public PublicController(
ILogger&lt;PublicController&gt; logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
validationProvider
)
{
}
[HttpGet]
[Route("Items")]
public IActionResult Items()
{
return Ok("Public endpoint.");
}
}</code></pre>
<h3>۱۳.۳. روش سوم: استفاده سراسری با Middleware و appsettings</h3>
<p>
در این روش کافی است تنظیمات <code class="inline">XRateLimit</code> در
<code class="inline">appsettings.json</code> وجود داشته باشد و Middleware فعال شود.
</p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
//
services.AddXCommons(Configuration);
services.AddXRateLimit(Configuration);
//
services.AddControllers();
}
public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env
)
{
//
app.UseRouting();
//
// اگر KeyMode = User دارید، Authentication باید قبل از RateLimit باشد.
app.UseAuthentication();
//
app.UseXRateLimit();
//
app.UseAuthorization();
//
app.UseEndpoints(endpoints =&gt;
{
endpoints.MapControllers();
});
}</code></pre>
<h3>۱۳.۴. روش چهارم: استفاده دستی در Controller یا Service</h3>
<pre><code>using xCommons.Models;
using xCommons.Interfaces;
using xCommons.Controllers;
using Microsoft.AspNetCore.Mvc;
namespace xSaherelm.Api.Controllers
{
public class ManualRateLimitController : XBaseApiV1Controller
{
private readonly IXRateLimitProvider rateLimitProvider;
public ManualRateLimitController(
ILogger&lt;ManualRateLimitController&gt; logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider,
IXRateLimitProvider rateLimitProvider
) : base(
logger,
appConfiguration,
validationProvider
)
{
this.rateLimitProvider = rateLimitProvider;
}
[HttpGet]
[Route("Manual")]
public IActionResult Manual()
{
//
var key = $"manual:{GetControllerName()}";
var result = rateLimitProvider.TryConsume(
key: key,
limit: 10,
periodSeconds: 60
);
//
if (!result.IsAllowed)
{
return StatusCode(429, new
{
message = "Too many requests.",
retryAfter = result.RetryAfterSeconds,
resetOn = result.ResetOn
});
}
//
return Ok(new
{
message = "Manual RateLimit passed.",
remaining = result.Remaining,
resetOn = result.ResetOn
});
}
}
}</code></pre>
<h3>۱۳.۵. روش پنجم: قانون‌محور بر اساس PathPrefix</h3>
<p>
با تنظیمات نمونه، هر درخواست به مسیرهایی که با
<code class="inline">/api/v1/auth</code> شروع می‌شوند حداکثر ۵ بار در دقیقه بر اساس IP
مجاز است. مسیرهای <code class="inline">/api/v1/public</code> بر اساس ClientId
حداکثر ۳۰ بار در دقیقه مجاز هستند.
</p>
</section>
<section class="card" id="notes">
<h2>۱۴. نکات مهم و محدودیت‌ها</h2>
<ul>
<li>
<strong>IMemoryCache توزیع‌شده نیست:</strong> اگر برنامه روی چند Instance اجرا می‌شود،
شمارنده‌ها بین Instanceها مشترک نیستند. برای محیط توزیع‌شده باید Provider را با Redis
یا یک Store متمرکز پیاده‌سازی کرد.
</li>
<li>
<strong>Real IP پشت Proxy:</strong> در صورت قرار گرفتن برنامه پشت Nginx یا Load Balancer،
باید هدر <code class="inline">X-Forwarded-For</code> یا
<code class="inline">X-Real-IP</code> به‌درستی پیکربندی و در استخراج کلید استفاده شود.
</li>
<li>
<strong>ترتیب Middleware:</strong> برای استفاده از <code class="inline">KeyMode = User</code>
باید <code class="inline">UseAuthentication</code> قبل از
<code class="inline">UseXRateLimit</code> باشد.
</li>
<li>
<strong>جلوگیری از Double Count:</strong> اگر روی Action از
<code class="inline">[XRateLimit]</code> استفاده می‌کنید، Middleware به‌صورت خودکار
وجود Attribute روی Endpoint را تشخیص داده و از اعمال دوباره صرف‌نظر می‌کند.
</li>
<li>
<strong>هدرهای خروجی:</strong> هدرهای
<code class="inline">X-RateLimit-Limit</code>،
<code class="inline">X-RateLimit-Remaining</code>،
<code class="inline">X-RateLimit-Reset</code> و در صورت مسدود شدن
<code class="inline">Retry-After</code> تنظیم می‌شوند.
</li>
<li>
<strong>پاک‌سازی قفل‌ها:</strong> با RegisterPostEvictionCallback، قفل مربوط به هر Key
پس از انقضای Entry از <code class="inline">ConcurrentDictionary</code> حذف می‌شود.
</li>
<li>
<strong>سازگاری با ASP.NET Core 3.1:</strong> کد جدید از قابلیت‌های نسخه‌های بالاتر
مانند <code class="inline">AddRateLimiter</code> استفاده نمی‌کند و با
<code class="inline">IMemoryCache</code> و Middleware/Filterهای 3.1 سازگار است.
</li>
</ul>
<div class="note danger">
<strong>توصیه امنیتی:</strong> RateLimit جایگزین Authentication و Authorization نیست.
این قابلیت باید در کنار احراز هویت، اعتبارسنجی ورودی، CORS صحیح و Logging مناسب استفاده شود.
</div>
</section>
</main>
</div>
</div>
</body>
</html>