۱. خلاصه مدیریتی
در ASP.NET Core 3.1 قابلیت Rate Limiting توکار با
AddRateLimiter و
UseRateLimiter وجود ندارد؛ این قابلیت از .NET 7 به بعد اضافه شده است.
بنابراین برای این ماژول، یک پیادهسازی سفارشی مطابق با سبک کدنویسی موجود در
xCommons طراحی شده است.
راهکار پیشنهادی شامل این اجزا است:
- یک Provider مبتنی بر
IMemoryCacheبرای نگهداری شمارنده درخواستها. - یک Attribute برای اعمال RateLimit روی Controller یا Action.
- یک Middleware برای اعمال RateLimit سراسری بر اساس قوانین تنظیمات.
- استفاده دستی از Provider در Controller یا Service برای سناریوهای خاص.
- پشتیبانی از کلید محدودسازی بر اساس IP، ClientId، User و Route.
partial class،
extension method،
XException.InvalidArgs.Throw()،
IsNull/IsNullOrEmpty/HasChild/ToNormalString
و ساختار Namespaceهای موجود هماهنگ است.
۲. بررسی کامل سورس ارائهشده
سورس ارائهشده شامل زیرساختهای مشترک ماژول xCommons است. این ماژول نقش پایه مشترک بین پروژهها را دارد و شامل Attributeها، Authorization، Configuration، Constants، Controllerهای پایه، DI، Extensionها، Filterها، Helperها، Interfaceها، Modelها و Providerها است.
۲.۱. نقشه فایلها و مسئولیتها
| گروه | فایلهای کلیدی | مسئولیت |
|---|---|---|
| Attributes | RequireXPoweredAttribute.cs |
فیلتر احراز هدر X-PoweredBy با پشتیبانی از AllowAnonymous. |
| Authorization | RequiredRolesHandler.cs، RequiredRolesRequirement.cs |
پیادهسازی Authorization مبتنی بر Role Claim. |
| Configurations | XAppConfiguration.cs، XSwaggerConfiguration.cs، XFileTypeDetectorConfiguration.cs |
مدلهای تنظیمات برنامه و سرویسهای جانبی. |
| Constants | ConfigurationNodeNames.cs، XAuthorization.cs، XCustomClaims.cs، XPolicy.cs |
ثابتهای نام Node تنظیمات، هدرها، Claimها و Policyها. |
| Controllers | XBaseController.cs، XBaseApiController.cs، XBaseApiV1Controller.cs |
Controllerهای پایه با Route، Produces، RequireXPowered و ابزارهای خطا. |
| DI | XDIHelperExtension.cs، DIExtensions.cs |
ثبت سرویسهای ماژول، Swagger، CORS، Versioning و FileTypeDetector. |
| Extensions | CommonExtensions.cs، IConfigurationExtensions.cs، XHttpExtensions.cs، FilterExtensions.cs |
Extensionهای عمومی، خواندن تنظیمات، HTTP، Filter و ... . |
| Filters | RequireXPoweredOperationFilter.cs، SwaggerDefaultValuesOperationFilter.cs |
OperationFilterهای Swagger. |
| Helpers | XFileHelper.cs، XReflectionHelper.cs، XOsHelper.cs، XNetworkHelper.cs |
ابزارهای فایل، Reflection، OS و Network. |
| Interfaces | IXCipher.cs، IXFileTypeDetector.cs |
قراردادهای سرویسهای رمزنگاری و تشخیص نوع فایل. |
| Models | XFileTypeInfo.cs، XFileTypeDetectionResult.cs، XLoggerModel.cs |
مدلهای داده مشترک. |
| Providers | XFileTypeDetector.cs، XCipher.cs، XValidationProvider.cs، XBackgroundService.cs |
پیادهسازی سرویسها و BackgroundServiceهای پایه. |
۲.۲. نکات معماری استخراجشده
- استفاده گسترده از
partial classوpartial structبرای توسعهپذیری. - استفاده از
extension methodبرای عملیات عمومی مانند Null Check، JSON، String، Configuration و HTTP. - تنظیمات بهصورت POCO تعریف میشوند و با Extensionهای
IConfigurationخوانده میشوند. - خطاها با
XExceptionو متدهای الحاقیThrow()مدیریت میشوند. - اعتبارسنجی ورودیها با
XValidationProviderانجام میشود. - ثبت سرویسها با Extensionهای
IServiceCollectionو نامگذاریAddX...انجام میشود. - فیلترها و Attributeها از
RequestServicesبرای دسترسی به سرویسها استفاده میکنند. - نامگذاریها با پیشوند
Xو NamespaceهایxCommons.*ادامه یافته است.
۲.۳. نکات قابل توجه در سورس فعلی
-
XMiddlewareExtensions.csدر حال حاضر خالی و غیر partial است؛ برای افزودنUseXRateLimitباید بهpublic static partial classتغییر کند. -
XHttpContextExtensions.csاز قبل partial است؛ بنابراین افزودن Extensionهای RateLimit در همان کلاس امکانپذیر است. -
IConfigurationExtensions.csاز قبل partial است؛ افزودنGetXRateLimitConfigurationدر فایل جداگانه امکانپذیر است. -
DIExtensions.csاز قبل partial است؛ افزودنAddXRateLimitدر همان کلاس انجام میشود. -
برای سازگاری با ASP.NET Core 3.1 در کد جدید از Target-typed
new()استفاده نشده و در صورت نیاز از نوع صریح استفاده شده است.
۳. الگوهای کدنویسی مورد استفاده در پیادهسازی
| الگو | نمونه در کد جدید |
|---|---|
| Partial Class/Struct | public partial class XRateLimitProvider |
| Extension Method | GetXRateLimitKey(this HttpContext ...) |
| DI Extension | AddXRateLimit(this IServiceCollection ...) |
| Middleware Extension | UseXRateLimit(this IApplicationBuilder ...) |
| Null-safe Helperها | IsNull()، IsNullOrEmpty()، ToNormalString() |
| خطای استاندارد | XException.InvalidArgs.Throw() |
| تنظیمات POCO | XRateLimitConfiguration، XRateLimitRule |
۴. طراحی RateLimit سفارشی
جریان کلی درخواست به شکل زیر است:
۴.۱. اجزای طراحیشده
- XRateLimit: ثابتهای Cache Key، نام هدرها و کلید Item.
- XRateLimitKeyMode: حالت انتخاب کلید شامل IP، ClientId، User، Route و Custom.
- XRateLimitRule: قانون محدودسازی برای یک PathPrefix مشخص.
- XRateLimitConfiguration: تنظیمات کلی و لیست قوانین.
- XRateLimitResult: نتیجه بررسی شامل Allow/Deny، Remaining، RetryAfter و ResetOn.
- XRateLimitCounter: شمارنده ذخیرهشده در IMemoryCache.
- IXRateLimitProvider: قرارداد مصرف RateLimit.
- XRateLimitProvider: پیادهسازی مبتنی بر IMemoryCache و lock.
- XRateLimitAttribute: اعمال RateLimit روی Action/Controller.
- XRateLimitMiddleware: اعمال RateLimit سراسری بر اساس قوانین.
۵. پیادهسازی گامبهگام
- افزودن تنظیمات
XRateLimitبهappsettings.json. - افزودن ثابتهای جدید به
ConstantsوConfigurationNodeNames. - ایجاد مدلهای تنظیمات، نتیجه و شمارنده.
- ایجاد Interface برای Provider.
- پیادهسازی Provider با
IMemoryCache. - افزودن Extension برای استخراج کلید RateLimit از
HttpContext. - ایجاد Attribute برای Controller/Action.
- ایجاد Middleware سراسری.
- افزودن Extension خواندن تنظیمات و ثبت DI.
- فعالسازی Middleware در
Startup.csو استفاده در Controller.
۶. تنظیمات appsettings.json
نمونه تنظیمات زیر را به فایل appsettings.json اضافه کنید.
اگر ApplyToAllRoutes برابر true باشد،
برای همه Routeها از مقدار Default استفاده میشود. در غیر این صورت فقط Rules منطبق اعمال میشوند.
{
"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
}
]
}
}
۷. Constants و Configuration
۷.۱. فایل جدید: Constants/XRateLimit.cs
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";
}
}
۷.۲. فایل جدید: Constants/XRateLimitKeyMode.cs
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
}
}
۷.۳. تغییر در Constants/ConfigurationNodeNames.cs
یک ثابت برای نام Node تنظیمات RateLimit اضافه کنید:
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";
}
}
۷.۴. فایل جدید: Configurations/XRateLimitConfiguration.cs
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<XRateLimitRule> Rules { get; set; } = new List<XRateLimitRule>();
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;
}
}
۸. Models و Interface
۸.۱. فایل جدید: Models/XRateLimitResult.cs
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; }
}
}
۸.۲. فایل جدید: Models/XRateLimitCounter.cs
using System;
namespace xCommons.Models
{
public partial class XRateLimitCounter
{
public int Count { get; set; }
public int Limit { get; set; }
public DateTimeOffset ResetOn { get; set; }
}
}
۸.۳. فایل جدید: Interfaces/IXRateLimitProvider.cs
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
);
}
}
۹. Provider مبتنی بر IMemoryCache
این کلاس شمارندهها را در IMemoryCache نگهداری میکند.
برای جلوگیری از Race Condition از یک lock به ازای هر Cache Key
استفاده شده است. همچنین هنگام Evict شدن Entry، قفل مربوطه نیز پاک میشود.
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<string, object> syncRoots =
new ConcurrentDictionary<string, object>();
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 <= 0 || periodSeconds <= 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: _ => new object()
);
//
lock (syncRoot)
{
//
var counter = cache.Get<XRateLimitCounter>(normalizedKey);
if (counter.IsNull() || counter.ResetOn <= 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 <= 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) =>
{
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
);
}
}
}
۱۰. Attribute برای Controller/Action
این Attribute از نوع IActionFilter است و سرویسها را از
RequestServices دریافت میکند. اگر هم Attribute و هم Middleware
فعال باشند، Middleware بهصورت خودکار وجود Attribute روی Endpoint را تشخیص داده و از
اعمال دوباره صرفنظر میکند.
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<IXRateLimitProvider>();
var configuration = context.HttpContext.RequestServices
.GetService<XRateLimitConfiguration>();
//
if (provider.IsNull() ||
configuration.IsNull() ||
!provider.IsEnabled)
{
return;
}
//
var limit = Limit > 0
? Limit
: configuration.DefaultLimit;
var periodSeconds = PeriodSeconds > 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();
}
}
}
}
۱۰.۱. Extension استخراج کلید RateLimit
فایل جدید: Extensions/XRateLimitHttpContextExtensions.cs
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();
}
}
}
}
}
۱۱. Middleware سراسری
این Middleware باید بعد از UseRouting و در صورت استفاده از
KeyMode = User بعد از UseAuthentication
و قبل از UseAuthorization ثبت شود.
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<XRateLimitAttribute>()
.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();
}
}
}
}
۱۲. ثبت DI و Middleware
۱۲.۱. افزودن Extension خواندن تنظیمات
فایل جدید: Extensions/IConfigurationExtensions.XRateLimit.cs
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<XRateLimitConfiguration>();
if (result.IsNull())
{
result = new XRateLimitConfiguration();
}
//
if (result.Rules.IsNull())
{
result.Rules = new List<XRateLimitRule>();
}
//
return result;
}
}
}
۱۲.۲. افزودن Extension ثبت DI
فایل جدید: Extensions/DIExtensions.XRateLimit.cs
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<IXRateLimitProvider, XRateLimitProvider>();
}
}
}
۱۲.۳. تغییر در Extensions/XMiddlewareExtensions.cs
این فایل باید به partial تبدیل شود و متد
UseXRateLimit به آن اضافه شود:
using xCommons.Middlewares;
using Microsoft.AspNetCore.Builder;
namespace xCommons.Extensions
{
public static partial class XMiddlewareExtensions
{
public static void UseXRateLimit(
this IApplicationBuilder source
)
{
//
source.UseMiddleware<XRateLimitMiddleware>();
}
}
}
۱۳. روشهای استفاده
۱۳.۱. روش اول: استفاده از Attribute روی Action
using xCommons.Constants;
using xCommons.Attributes;
using xCommons.Controllers;
using Microsoft.AspNetCore.Mvc;
namespace xSaherelm.Api.Controllers
{
public class AuthController : XBaseApiV1Controller
{
public AuthController(
ILogger<AuthController> 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.");
}
}
}
۱۳.۲. روش دوم: استفاده از Attribute روی Controller
[XRateLimit(
Limit = 30,
PeriodSeconds = 60,
KeyMode = XRateLimitKeyMode.ClientId
)]
public class PublicController : XBaseApiV1Controller
{
public PublicController(
ILogger<PublicController> logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
validationProvider
)
{
}
[HttpGet]
[Route("Items")]
public IActionResult Items()
{
return Ok("Public endpoint.");
}
}
۱۳.۳. روش سوم: استفاده سراسری با Middleware و appsettings
در این روش کافی است تنظیمات XRateLimit در
appsettings.json وجود داشته باشد و Middleware فعال شود.
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 =>
{
endpoints.MapControllers();
});
}
۱۳.۴. روش چهارم: استفاده دستی در Controller یا Service
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<ManualRateLimitController> 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
});
}
}
}
۱۳.۵. روش پنجم: قانونمحور بر اساس PathPrefix
با تنظیمات نمونه، هر درخواست به مسیرهایی که با
/api/v1/auth شروع میشوند حداکثر ۵ بار در دقیقه بر اساس IP
مجاز است. مسیرهای /api/v1/public بر اساس ClientId
حداکثر ۳۰ بار در دقیقه مجاز هستند.
۱۴. نکات مهم و محدودیتها
- IMemoryCache توزیعشده نیست: اگر برنامه روی چند Instance اجرا میشود، شمارندهها بین Instanceها مشترک نیستند. برای محیط توزیعشده باید Provider را با Redis یا یک Store متمرکز پیادهسازی کرد.
-
Real IP پشت Proxy: در صورت قرار گرفتن برنامه پشت Nginx یا Load Balancer،
باید هدر
X-Forwarded-ForیاX-Real-IPبهدرستی پیکربندی و در استخراج کلید استفاده شود. -
ترتیب Middleware: برای استفاده از
KeyMode = UserبایدUseAuthenticationقبل ازUseXRateLimitباشد. -
جلوگیری از Double Count: اگر روی Action از
[XRateLimit]استفاده میکنید، Middleware بهصورت خودکار وجود Attribute روی Endpoint را تشخیص داده و از اعمال دوباره صرفنظر میکند. -
هدرهای خروجی: هدرهای
X-RateLimit-Limit،X-RateLimit-Remaining،X-RateLimit-Resetو در صورت مسدود شدنRetry-Afterتنظیم میشوند. -
پاکسازی قفلها: با RegisterPostEvictionCallback، قفل مربوط به هر Key
پس از انقضای Entry از
ConcurrentDictionaryحذف میشود. -
سازگاری با ASP.NET Core 3.1: کد جدید از قابلیتهای نسخههای بالاتر
مانند
AddRateLimiterاستفاده نمیکند و باIMemoryCacheو Middleware/Filterهای 3.1 سازگار است.