Adding RateLimit Feature ...
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
using System.Linq;
|
||||
using xCommons.Configurations;
|
||||
|
||||
namespace xCommons.Extensions
|
||||
{
|
||||
public static class XCommonsExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Extract RateLimit Rule based on given Path ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="path"></param>
|
||||
/// <returns></returns>
|
||||
public static XRateLimitRule GetMatchingRule(
|
||||
this XRateLimitConfiguration source,
|
||||
string path
|
||||
)
|
||||
{
|
||||
//
|
||||
if (!source.Enabled)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
var normalizedPath = path.IsNullOrEmpty()
|
||||
? "/"
|
||||
: path.ToNormalString();
|
||||
|
||||
//
|
||||
var rule = source.Rules.IsNull()
|
||||
? null
|
||||
: source.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 (source.ApplyToAllRoutes)
|
||||
{
|
||||
//
|
||||
return new XRateLimitRule
|
||||
{
|
||||
Enabled = true,
|
||||
Name = "Default",
|
||||
PathPrefix = "/",
|
||||
Limit = source.DefaultLimit,
|
||||
KeyMode = source.DefaultKeyMode,
|
||||
PeriodSeconds = source.DefaultPeriodSeconds,
|
||||
};
|
||||
}
|
||||
|
||||
//
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user