Middleware allows us to shape the request structures and response structures from the client.
- Routing
- Authentication
- Authorization
- Logging
These items can be made middleware constructs.
For example;
Middleware Imp.
We have an Api project.
Our aim is to check whether there are Client-Key, Client-Id, key-value parameters in the header section of the request models that will come to this api and to write middleware for the response that returns according to the presence of the parameters.
HeaderCheckMiddleware class is created.
public class HeaderCheckMiddleware
{
private readonly RequestDelegate _next;
public HeaderCheckMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
var key1 = httpContext.Request.Headers.Keys.Contains("Client-Key");
var key2 = httpContext.Request.Headers.Keys.Contains("Device-Id");
if (!key1 || !key2)
{
httpContext.Response.StatusCode = 400;
await httpContext.Response.WriteAsync("Missing requeired keys !");
return;
}
else
{
//todo
}
await _next.Invoke(httpContext);
}
}
The Invoke method allows us to intervene in the incoming request and response. In this scenario, if there are no parameters we want in the header of the incoming request model, we return 400 bad request.
In step 2, we write extension method for HeaderCheckMiddleware class. We are writing a static method because we want to add it to program.cs and we want the middleware to run when the system runs.
public static class MiddlewareExtension
{
public static IApplicationBuilder UseHeaderCheckMiddleware
(this IApplicationBuilder builder)
{
return builder.UseMiddleware<HeaderCheckMiddleware>();
}
}
In step 3, we use this static method in program.cs.
And let’s we see the responses.
400 — Bad Request
200 — OK
Thanks for reading…
Ahmet Muhsinoglu.
Top comments (0)