Implement Rate Limiting In ASP.NET Core Web API

Image
Introduction In this article, you'll learn about rate limiting and how to apply it to your ASP.NET Core Web API. What is Rate Limiting? If you're building an API, it might be accessed by multiple clients. Sometimes, certain clients use the API excessively without any restrictions. However, if you need to control how often a specific client can use the API within a set timeframe, you can achieve this through Rate Limiting. Rate Limiting is like setting a speed limit on how many times someone can ask for something from a website or app in a certain amount of time. It means each person or device using the service can only ask for a certain number of things within a particular timeframe. Why do we need Rate Limiting? Rate Limiting is a useful tool for safeguarding against harmful bot attacks. Imagine a hacker sending bots to repeatedly request access to an API endpoint. This flood of requests can ove...

Custom Middleware in .Net core 6.0

 

We will now write a custom middleware to avoid inline middleware in Program.cs.  The custom middleware will be written to a different class. Please keep the following in mind when writing custom middleware.

There are several components that must be included in the middleware class:

  • RequestDelegate is a public constructor with a parameter.
  • Invoke or InvokeAsync is a public method that should return a Task.
  • HttpContext should be the first parameter
  • With IApplicationBuilder, an extension method is created for exposing the Middleware.
  • Dependency Injection can be used to populate additional parameters for the constructor and for Invok/InvokeAsync.


Let's quickly dive into Visual Studio and start building a middleware. In this tutorial, I'll be utilizing the following tools:

  • Visual Studio Community Edition 2022 (64-bit)
  • .NET 6.0
  • Minimal Web API
  • Swagger


There are three different methods or approaches you can use to create your own custom middleware.

Method 1

  • First of all you can Right Click on the Project -> Add -> New Item.
  • After You will find out for that Middleware in the Pop-up window.
  • then, Select the Middleware class and given the proper name and click on 'Add'.

Add Middleware

A class will be created in this way with the default implementation:


 
 		namespace CustomMiddleware
{
    
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;

        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {

            return _next(httpContext);
        }
    }

    
    public static class CustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomMiddleware>();
        }
    }
}     
      


Method 2
  • Insert a new class with a significant name.
  • Add the public constructor using the RequestDelegate argument.
  • Implement an Invoke/InvokeAsync method with a first parameter of HttpContext and a return type of Task.
  • Add a method of extension through IApplicationBuilder to expose the middleware.

  namespace CustomMiddleware
{
    public class NoImplementationCustomMiddleware
    {
        private readonly RequestDelegate _next;
        public NoImplementationCustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task InvokeAsync(HttpContext httpContext)
        {
            await httpContext.Response.WriteAsync("Hello Friends !, this is my Customer Middleware...");
        }
    }
   
    public static class NoImplementationCustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseClassWithNoImplementationMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<NoImplementationCustomMiddleware>();
        }
    }
}
  

Method 3
  • Insert a new class with a significant name.
  • Now Implement of the interface of the Middleware

        namespace CustomMiddleware
{
    public class ICustomMiddlewareWithInterface : IMiddleware
    {
        public Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            throw new NotImplementedException();
        }
    }
}
        


Now we can use the Custom Middleware into the Program.cs

        using CustomMiddleware;

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseClassWithNoImplementationMiddleware();
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
//app.UseStaticFiles();

//app.UseRouting();

//app.UseAuthorization();

//app.MapRazorPages();

app.Run();

        

Comments

Popular posts from this blog

Implement Rate Limiting In ASP.NET Core Web API

.Net Core vs .Net framework

The Key Features of .Net 8