Adding [FromHeader(Name = "<header-name>")
attribute is crutial for reading the headers on the controller level.
public class TodoHeaders
{
[FromHeader(Name = "header1")]
public string? Header1 { get; set; }
[FromHeader(Name = "header2")]
public string? Header2 { get; set; }
}
[Route("Create")]
[HttpPost]
public ActionResult<Todo> CreateTodo([FromBody] CreateTodoDTO todoDTO, [FromHeader] TodoHeaders todoHeaders)
{ }
namespace APIDocs.Middlewares
{
public class RequestHeaderMiddleware
{
private readonly RequestDelegate _next;
public RequestHeaderMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Read headers from the request
string headerValue = context.Request.Headers["header1"];
string headerValue2 = context.Request.Headers["header2"];
// Do something with the header value
// Call the next middleware in the pipeline
await _next(context);
}
}
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseMiddleware<RequestHeaderMiddleware>(); // <--- Here it is
app.MapControllers();