Use IP based request limit action filter
We can limit customers to a certain number of requests over a specified period of time to prevent malicious bot attacks.We havecreated IP based requestlimitactionfilter in the ASP.NET Core. Keep in mind that multiple clients can sit behind a single IP address so you can meet this within your limits, or combine the IP address with other request data to make requests more unique.
To try the filter, you just need to add an ActionAttribute at the top of the controller action.
[HttpGet()]
[ValidateReferrer]
[RequestLimit("Test-Action", NoOfRequest = 3, Seconds = 10)]
publicasync TaskGetAsync(CancellationTokenct)
{
// code here
}
Here is the implementation of the filter:
namespace Security.Api.Filters
{
using System;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
[AttributeUsage(AttributeTargets.Method)]
public class RequestAttribute :ActionFilterAttribute
{
public RequestAttribute(string name)
{
Name = name;
}
public string Name
{
get;
}
public intNoOfRequest
{
get;
set;
} = 1;
public int Seconds
{
get;
set;
} = 1;
private static MemoryCachememoryCache
{
get;
} = new MemoryCache(new MemoryCacheOptions());
public override void OnActionExecuting(ActionExecutingContext context)
{
varipAddress = context.HttpContext.Request.HttpContext.Connection.RemoteIpAddress;
varmemoryCacheKey = $ "{Name}-{ipAddress}";
memoryCache.TryGetValue(memoryCacheKey, out intprevReqCount);
if (prevReqCount>= NoOfRequest)
{
context.Result = new ContentResult
{
Content = $ "Request is exceeded. Try again in seconds.",
};
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.TooManyRequests;
}
else
{
varcacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(Seconds));
memoryCache.Set(memoryCacheKey, (prevReqCount + 1), cacheEntryOptions);
}
}
}
}