Adding RateLimit Feature ...
This commit is contained in:
@@ -1,22 +1,105 @@
|
||||
using System.IO;
|
||||
using xCommons.Constants;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace xCommons.Extensions {
|
||||
public static partial class XHttpContextExtensions {
|
||||
namespace xCommons.Extensions
|
||||
{
|
||||
public static partial class XHttpContextExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Convert IFormFile to Bytes Array
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static byte[] ToByteArray (this IFormFile source) {
|
||||
public static byte[] ToByteArray(this IFormFile source)
|
||||
{
|
||||
//
|
||||
byte[] data;
|
||||
using (var br = new BinaryReader (source.OpenReadStream ())) {
|
||||
data = br.ReadBytes ((int) source.OpenReadStream ().Length);
|
||||
using (var br = new BinaryReader(source.OpenReadStream()))
|
||||
{
|
||||
data = br.ReadBytes((int)source.OpenReadStream().Length);
|
||||
}
|
||||
|
||||
//
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract Rate Limit Key ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="keyMode"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetXRateLimitKey(
|
||||
this HttpContext source,
|
||||
XRateLimitKeyMode keyMode
|
||||
)
|
||||
{
|
||||
//
|
||||
if (source.IsNull())
|
||||
{
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
//
|
||||
switch (keyMode)
|
||||
{
|
||||
//
|
||||
case XRateLimitKeyMode.ClientId:
|
||||
{
|
||||
//
|
||||
var clientId = source.Request.Headers[XRateLimitConstants.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user