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

问题描述 投票:1回答:2

我在.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);
    }
}

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

没有任何作用,为了使中间件工作,我缺少什么?

.net asp.net-core .net-core
2个回答
4
投票

您应该将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");
}

2
投票

订购中间件注册。因此,在MVC之前注册的任何内容都将在MVC之前运行。

如果请求与MVC可以处理的URL匹配,则MVC处理该请求。如果MVC无法匹配URL,您在MVC之后注册的任何内容都只会处理请求。

© www.soinside.com 2019 - 2024. All rights reserved.