Search code examples
asp.netasp.net-mvcowin-middleware

Why isnt my middleware working?


I've tried to add my own middleware, it does not work :-)

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        System.Diagnostics.Debug.WriteLine("OWIN IS WORKING");

        app.Use<CustomMiddleware>();
    }
}

public class CustomMiddleware
{
    public async Task Invoke(HttpContext context)
    {
        string token = context.Request.Headers["Authorization"];
    }
}

The WriteLine is so it enters the Configuration per request to the server, but my CustomMiddleware Invoke aint triggered.

Anye clue?


Solution

  • You need constructor have next delegate.

    So your code should change like the below:

    public class CustomMiddleware 
    {
        private readonly RequestDelegate _next;
    
        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
            string token = context.Request.Headers["Authorization"];
            await _next();
        }
    }