There is currently a NuGet package that manages rate limiting by IP address called AspNetCoreRateLimit. However, .NET 7 introduced its own version of rate limiting and I wanted to use this instead as it is published by MS. I have not been able to find a good example that imitates this third party package by limiting by IP address. The code I put together is as follows:
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = 429;
options.AddPolicy("api", httpContext =>
{
var IpAddress = httpContext.Connection.RemoteIpAddress.ToString();
if (IpAddress != null)
{
return RateLimitPartition.GetFixedWindowLimiter(httpContext.Connection.RemoteIpAddress.ToString(),
partition => new FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1)
});
}
else
{
return RateLimitPartition.GetNoLimiter("");
}
});
});
However, the issue I am getting is a warning "Warning CS8602: Dereference of a possibly null reference." which I assume is because RemoteIpAddress could be null. I am curious if there is a better way to implement this IP rate limiting using this new .NET 7 library. If it matters, I am planning to host this web api in Azure app services (windows) and it is accessed by a SPA also hosted in an app service.
IpAddress
as a fixed IP to test to see if it works? – Hacking