Skip to content

Instantly share code, notes, and snippets.

@MirzaLeka
Created March 10, 2024 11:15
Show Gist options
  • Save MirzaLeka/5b7bf63eb8033d3e77cfdaaa719abf34 to your computer and use it in GitHub Desktop.
Save MirzaLeka/5b7bf63eb8033d3e77cfdaaa719abf34 to your computer and use it in GitHub Desktop.

C# Web API Read Request Headers from Middleware and Controller

Headers Model

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; }
	}

Controller

		[Route("Create")]
		[HttpPost]
		public ActionResult<Todo> CreateTodo([FromBody] CreateTodoDTO todoDTO, [FromHeader] TodoHeaders todoHeaders)
		{ }

Middleware

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);
   	}
   }

}

Middleware in Program.cs

			app.UseHttpsRedirection();

   		app.UseAuthorization();

   		app.UseMiddleware<RequestHeaderMiddleware>(); // <--- Here it is

   		app.MapControllers();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment