What is Middleware, Why should we use it?
Middleware, the filters used at the time of the Framework are the structures that are triggered when our server receives a request or a response is sent from our server.
For example, when trying to navigate to an ActionResult to list users, the middleware first catches the request and then sends it to the ActionResult. After the ActionResult has finished its work, the client can get this information. You can control these requests according to your various needs. In the example we will give, we will make an application that prints the address of the incoming requests to the console. You can also do various controls by reading your HttpContext here.
public sealed class RequestMiddleware
{
private readonly RequestDelegate _next;
public RequestMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext context)
{
Console.WriteLine(context.Request.Path);
return _next(context);
}
}
Let's add the class we mentioned above in Startup.cs.
public class Startup
{
public void Configure(IApplicationBuilder app)
{
//...
app.UseMiddleware<RequestMiddleware>();
//...
}
}