.net核心-中间件不处理请求

Thu*_*olt 1 .net .net-core asp.net-core

我在.Net Core 2中遇到中间件问题。中间件无法处理任何即将到来的请求。我已经实现了。

KeyValidatorMiddleware类:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

并在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>();
}
Run Code Online (Sandbox Code Playgroud)

没有任何效果,为了使中间件正常工作,我缺少什么?

Dav*_*idG 6

您应该将UseMiddleware行移动到离顶部最近的位置,中间件按顺序运行,并且可能会在MVC级别停止。

例如:

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");
}
Run Code Online (Sandbox Code Playgroud)

  • OP:略有保留,但是您还将要根据此信息重新考虑`app.UseCors`的去向(实际上是`app.UseHttpsRedirection`)。 (2认同)