/ mono

ASP.net vNext Add Request Headers

Adding Request Headers

This article assumes you have either followed my previous article on adding Response Headers, or are comfortable with the locations of your projects files.
Previous Article on Adding Response Headers

Create Middleware Component

in ./Middleware/AddRequestHeaders.cs

using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;

namespace asp_vnext 
{
  public class AddRequestHeaders
  {
    RequestDelegate _next;
    
    public AddRequestHeaders(RequestDelegate next)
    {
      _next = next;
    }
		
    public async Task Invoke(HttpContext context) 
    {
      context.Request.Headers.Add("X-CustomRequestHeader","My Value Is Awesome!");
      await _next(context);
    }
  }
}

Add the following line inside Startup.cs Configure method

  app.UseMiddleware<AddRequestHeaders>();          

Create a route to show the behavior
I'm using the ValuesController.cs file that is created with a new base project created via Yeoman.

[HttpGet("echo/header")]
public string EchoCustomRequestHeader()
{
  return $"Request Header X-CustomerRequestHeader value {Request.Headers["X-CustomRequestHeader"]}";
}

Start up the web project

dnx web

Test the route

curl localhost:5000/api/values/echo/header

Result

Request Header X-CustomerRequestHeader value My Value Is Awesome!

Source Code for Project

ASP.net vNext Add Request Headers
Share this