.netasp.net-core.net-core

.net core - Middleware don't handle requests


I am having a problem with middleware in .Net Core 2. Middleware doesn't handle any coming requests. What I have implemented.

KeyValidatorMiddleware class:

public class KeyValidatorMiddleware
{
    private readonly RequestDelegate _next;

    public KeyValidatorMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {

        if (!context.Request.Headers.ContainsKey("api-key"))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("No API key found !");
            return;
        }

        await _next.Invoke(context);
    }
}

and in Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseMvc();
    app.UseCors("MyPolicy");
    app.UseMiddleware<KeyValidatorMiddleware>();
}

And nothing works, What am i missing in order to make the middleware work?


Solution

  • You should move the UseMiddleware line to be nearer the top, middleware runs in order and it may stop at the MVC level.

    For example:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
    
        app.UseMiddleware<KeyValidatorMiddleware>();
    
        app.UseHttpsRedirection();
        app.UseMvc();
        app.UseCors("MyPolicy");
    }