117 lines
3.5 KiB
C#
117 lines
3.5 KiB
C#
using System;
|
|
using xCommons.Models;
|
|
using xCommons.Constants;
|
|
using xCommons.Extensions;
|
|
using xCommons.Interfaces;
|
|
using xCommons.Configurations;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Http;
|
|
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 Order { get; set; } = -1000;
|
|
public int PeriodSeconds { get; set; } = 0;
|
|
public string KeyPrefix { get; set; } = null;
|
|
public XRateLimitKeyMode KeyMode { get; set; } = XRateLimitKeyMode.Ip;
|
|
|
|
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[XRateLimitConstants.AppliedItemKey] = true;
|
|
WriteHeaders(context.HttpContext, result);
|
|
|
|
//
|
|
if (!result.IsAllowed)
|
|
{
|
|
//
|
|
context.Result = new ObjectResult(new
|
|
{
|
|
resetOn = result.ResetOn,
|
|
retryAfter = result.RetryAfterSeconds,
|
|
message = "Too many requests. Please try again later.",
|
|
})
|
|
{
|
|
StatusCode = configuration.StatusCode
|
|
};
|
|
}
|
|
}
|
|
|
|
public void OnActionExecuted(ActionExecutedContext context)
|
|
{ }
|
|
|
|
private static void WriteHeaders(
|
|
HttpContext context,
|
|
XRateLimitResult result
|
|
)
|
|
{
|
|
//
|
|
context.Response.Headers[XRateLimitConstants.LimitHeader] =
|
|
result.Limit.ToString();
|
|
|
|
//
|
|
context.Response.Headers[XRateLimitConstants.RemainingHeader] =
|
|
result.Remaining.ToString();
|
|
|
|
//
|
|
context.Response.Headers[XRateLimitConstants.ResetHeader] =
|
|
result.ResetOn.ToUnixTimeSeconds().ToString();
|
|
|
|
//
|
|
if (!result.IsAllowed)
|
|
{
|
|
//
|
|
context.Response.Headers[XRateLimitConstants.RetryAfterHeader] =
|
|
result.RetryAfterSeconds.ToString();
|
|
}
|
|
}
|
|
}
|
|
} |