Tuesday 4 July 2023

ASP.NET Hosting Tutorial: Implementing Rate Limiting in .NET Core Web API using .NET 7.0

Leave a Comment

Rate limiting is a crucial component of scalability and security in web APIs. It aids in preventing abuse, safeguards server resources, and ensures equitable utilisation for all users. This article examines the implementation of bandwidth limiting in a.NET Core Web API application. We will cover the fundamentals of rate limiting, discuss various implementation strategies, and provide examples of its application.


What is Limiting Rates?
Rate limiting is a method that restricts the number of API requests a client can make within a given time frame. It limits the frequency with which clients can access particular endpoints or resources. By enforcing these limits, developers can prevent abuse, evenly distribute server burden, and preserve the quality of the user experience.

Using Rate Limiting with the.NET Core Web API
The AspNetCoreRateLimit library provides a robust and flexible solution for implementing rate limiting in.NET Core Web API applications. Let's delve into the detailed procedure.

Install the AspNetCoreRateLimit NuGet package in Step 1: Install the AspNetCoreRateLimit NuGet package to get started. The NuGet Package Manager in Visual Studio or the following command in the Package Manager Console can be utilised: Install the AspNetCoreRateLimit package.

Configure the Rate Limiting Middleware: Add the following code to the Program.cs file to enlist the rate-limiting services.

builder.Services.AddMemoryCache();
builder.Services.Configure < IpRateLimitOptions > (builder.Configuration.GetSection("IpRateLimiting"));
builder.Services.AddSingleton < IIpPolicyStore, MemoryCacheIpPolicyStore > ();
builder.Services.AddSingleton < IRateLimitCounterStore, MemoryCacheRateLimitCounterStore > ();
builder.Services.AddSingleton < IRateLimitConfiguration, RateLimitConfiguration > ();
builder.Services.AddInMemoryRateLimiting();

Step 3. Define Rate Limit Policies: In the appsettings.json file, add the following configuration to define rate limit policies.

"IpRateLimiting": {
  "EnableEndpointRateLimiting": true,
  "StackBlockedRequests": false,
  "RealIpHeader": "X-Real-IP",
  "ClientIdHeader": "X-ClientId",
  "HttpStatusCode": 429,
  "IpWhitelist": [],
  "EndpointWhitelist": [],
  "GeneralRules": [{
    "Endpoint": "GET:/WeatherForecast",
    "Period": "1m",
    "Limit": 10
  }]
}

By setting a general rule, we establish a default rate limit policy that applies to your API endpoints. This helps prevent excessive requests from any client or IP address and ensures fair usage and resource allocation. You can define additional policies and customize them according to your application's requirements.

Step 4. Enable Rate Limiting Middleware: In the Program.cs file, add the following code to enable rate-limiting middleware: app.UseIpRateLimiting();

Full Program.cs file code

using AspNetCoreRateLimit;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Services add for rate limiting
builder.Services.AddMemoryCache();
builder.Services.Configure < IpRateLimitOptions > (builder.Configuration.GetSection("IpRateLimiting"));
builder.Services.AddSingleton < IIpPolicyStore, MemoryCacheIpPolicyStore > ();
builder.Services.AddSingleton < IRateLimitCounterStore, MemoryCacheRateLimitCounterStore > ();
builder.Services.AddSingleton < IRateLimitConfiguration, RateLimitConfiguration > ();
builder.Services.AddInMemoryRateLimiting();

var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
  app.UseSwagger();
  app.UseSwaggerUI();
}
app.UseIpRateLimiting();
app.UseRouting();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Step 5. Test Rate Limiting

Now, we can test the rate-limiting implementation by making API requests. If a client exceeds the defined limits, they will receive a status code 429, "API calls quota exceeded! maximum admitted 10 per 1m." response.

Pros of Rate Limiting

  • Rate limiting helps protect your API from abusive behavior, such as excessive requests or denial-of-service attacks.
  • By limiting the number of requests per client or IP address, rate limiting helps prevent resource exhaustion and safeguards server performance.
  • By restricting the number of login attempts or requests to sensitive endpoints, rate limiting helps mitigate the risk of unauthorized access or data breaches.
  • Rate limiting allows API providers to implement different tiers or pricing plans based on usage. By setting different rate limits for various subscription levels or pricing tiers, you can offer differentiated services and monetize your API effectively.

Cons of Rate Limiting

  • Implementing rate limiting requires careful configuration and management. Determining the optimal rate limits, differentiating between client types, and handling edge cases can introduce complexity and additional overhead to the development and maintenance process.
  • In some cases, rate limiting can inadvertently affect users who require higher-than-average request rates. Stricter rate limits or misconfigurations may lead to users hitting rate limits and experiencing disruptions or reduced functionality.
  • Rate limiting introduces an additional layer of processing and checks for each incoming request, which can impact the overall performance of your API.

Rate limiting is an essential mechanism for protecting and assuring the stability and availability of your web API. In this article, we investigated how to use the AspNetCoreRateLimit library to implement rate limiting in a.NET Core Web API application. By following the steps enumerated in the preceding section, you can implement rate limits on API endpoints and prevent abuse or excessive usage.

Best ASP.NET Core 7.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 7.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core 7.0, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core 7.0 hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core 7.0. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.


0 comments:

Post a Comment