【问题标题】:.net core - Middleware don't handle requests.net core - 中间件不处理请求
【发布时间】:2018-09-14 21:56:39
【问题描述】:

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

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

【问题讨论】:

  • 您在管道的哪个位置添加了UseMiddleware 行?能给我们展示一个更完整的Configure方法吗?
  • UseMiddleware 行移到更靠近顶部的位置,中间件按顺序运行,它可能会停在MVC 级别。

标签: .net asp.net-core .net-core


【解决方案1】:

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

【讨论】:

  • OP:有点偏题,但您也需要根据这些信息重新考虑 app.UseCors 的去向(实际上是 app.UseHttpsRedirection)。
【解决方案2】:

已订购中间件的注册。所以你在 MVC 之前注册的任何东西都会在 MVC 之前运行。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-21
    • 2019-01-24
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多