Junior — Middle
Can you list and describe custom middleware you have created or used in your projects?
sobes.tech AI
Answer from AI
In C# projects using ASP.NET Core, I have created custom middleware to solve various tasks, such as:
-
Request and response logging: middleware intercepts HTTP requests and responses, recording important information (URL, method, execution time) for monitoring and debugging.
-
Error handling: middleware that catches exceptions occurring in the request processing pipeline and formats a unified error response.
-
Authentication and authorization: custom middleware for token verification or other authentication methods when standard solutions are not suitable.
Example of simple middleware for request logging:
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
public RequestLoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}");
await _next(context);
Console.WriteLine($"Response Status: {context.Response.StatusCode}");
}
}
// Registration in Startup.cs
// app.UseMiddleware<RequestLoggingMiddleware>();