What is Asp.Net middleware in its simplest definition?
Emre Kocadere
Posted on August 14, 2024
They are structures that make it possible to take customized actions on the Request/Response Pipeline
The request coming to your service does not immediately fall into the action method you wrote. It first passes through the middleware. Here you can change the requests coming to your service, check identity or keep a log record. There are already middleware in asp.net.
If you have analyzed the program.cs class of the asp.net project before, you will have seen that there are already midllewares there.
this is regular program.cs for asp.net web api projects
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
As the 2nd comment line says, you can configure Http request or response pipeline.
So the things in the pipeline image above;
app.UseHttpsRedirection(): This code is used to redirect HTTP requests to HTTPS.
app.UseAuthorization(): This code is used to set up authentication and authorization.
app.MapControllers(): This defines how your API responds to clients and how your controller classes are routed.
So how to add custom middleware to this pipeline?
How to Add Custom Middleware?
Middleware is actually a class and its structure is as follows.
public class CustomMiddleware
{
private readonly RequestDelegate _requestDelegate;
public CustomMiddleware(RequestDelegate requestDelegate)
{
_requestDelegate = requestDelegate;
}
public async Task Invoke(HttpContext context)
{
await _requestDelegate.Invoke(context);
}
}
The RequestDelegate: is required to run the next middleware. _requestDelegate.Invoke(context) function sends the http content to the next middleware
Invoke: This is the Method that will be Executed when Middleware is called. It allows us to handle in the Request coming to the application and the Response created.
You can change the response or request in it
HttpContext: It stores the request and response information, such as the properties of request.
For example, let's write a text to the console for every request coming to the service.
public async Task Invoke(HttpContext context)
{
Console.WriteLine("here is CustomMiddleware");
await _requestDelegate.Invoke(context);
}
Finally, we need to add this to the pipeline. For this, we add the middleware to program.cs.
app.UseMiddleware<CustomMiddleware>();
When I send any request, a log will be written to the console.
It doesn't matter which endpoint it goes to. Since every request will pass through middleware, it will be printed to the console with every request.
Or You can change the content of every response and request coming to your application whenever you want in Invoke method.
Let’s write a simple middleware that catches exceptions.
for that we need a Controller Class first.
public class ValuesController : ControllerBase
{
[HttpGet]
public int Get()
{
int a = 0;
int b = 15;
int c = b / a;
return c;
}
}
I created an error inside the controller class.
If this method works, the response will be as follows:
Now let's write a very simple middleware to prevent our application from crashing and to catch any missed exceptions.
public class CustomMiddleware
{
private readonly RequestDelegate _requestDelegate;
public CustomMiddleware(RequestDelegate requestDelegate)
{
_requestDelegate = requestDelegate;
}
public async Task Invoke(HttpContext context)//
{
try
{
await _requestDelegate.Invoke(context);
}
catch(Exception e) {
context.Response.StatusCode = 500;
await context.Response.WriteAsJsonAsync(e.Message);
}
}
}
add it to the pipeline
app.UseMiddleware<CustomMiddleware>();
After the middleware we wrote, the response will be as follows
Now the application continues without crashing.
why use middleware?
1.Requests can be passed through the desired controls
2.Solutions for Exception Handling can be provided
3.Authorization
4.Authentication
5.You can create logging mechanisms on the application.
Posted on August 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.