stefanprodan / AspNetCoreRateLimit

ASP.NET Core rate limiting middleware
MIT License
3.1k stars 444 forks source link

Getting CORS error instead of 429 (when using AspNetCoreRateLimit Nuget) #450

Open AssafKoh opened 1 year ago

AssafKoh commented 1 year ago

Hello,

I started using your Nuget: "AspNetCoreRateLimit", which controls the maximum number of requests to a certain API or to all APIs.

After the desired number of requests, the API is indeed blocked. for 3 requests I indeed see 429 as response status, but after the 3rd request and so on, I stop getting a 429 status and start getting a CORS error.

Do you have any idea why this is happening?

zhi-feng2008 commented 2 weeks ago

Hello!

To resolve the CORS issue you're experiencing after hitting the rate limit, you can try applying the CORS middleware globally before the rate-limiting middleware. Here’s how you can configure it:

// Apply CORS globally before any other middleware
app.UseCors("AllowAllOrigins");

// Apply the rate limiting middleware
app.UseIpRateLimiting();

app.UseRouting();

// ...

This approach ensures that even when a 429 status code is returned, the CORS headers are correctly included. However, this is just my method—I’m not sure if it fits your scenario, but I hope it helps!