【问题标题】:Can't GET any more after using custom middleware使用自定义中间件后无法再获取
【发布时间】:2018-03-01 16:07:30
【问题描述】:

我正在使用 .NET Core,但在实现自定义中间件时遇到了一些问题。我有一个中间件,它应该检查标题是否有一个名为“user-key”的字段。如果不是,则返回 400 错误。如果它确实有它,它应该给我请求的 GET,但它只是给我一个 404 错误。从我的 startup.cs 中删除中间件时,它再次工作,但我无法检查它是否有密钥。

ApiKeyMiddleWare.cs

public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        if (!context.Request.Headers.Keys.Contains("user-key"))
        {
            //Doesn't contain a key!
            context.Response.StatusCode = 400; //Bad request.
            await context.Response.WriteAsync("No API key found.");
            return;
        }
        else
        {
            //Contains key!
            //Check if key is valid here
            //if key isn't valid
            /*
            if(true == false)
            {

                context.Response.StatusCode = 401; //Unauthorized
                await context.Response.WriteAsync("Invalid API key found.");
                return;
            }
            */
        }

        await _next.Invoke(context);
    }
}

public static class ApiKeyMiddlewareExtension
{
    public static IApplicationBuilder ApplyApiKeyMiddleWare(this IApplicationBuilder app)
    {
        app.UseMiddleware<ApiKeyMiddleware>();
        return app;
    }
}

Startup.cs - 配置方法

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {


        app.MapWhen(context => context.Request.Path.StartsWithSegments("/api"), appBuilder =>
        {
            appBuilder.ApplyApiKeyMiddleWare();
        });

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();


        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });


        //Swagger
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });


    }

如果您需要更多信息,请告诉我。提前致谢!

【问题讨论】:

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


    【解决方案1】:

    您的中间件没问题,但您需要使用UseWhen 扩展方法而不是MapWhen 注册它。

    UseWhen:有条件地在请求管道中创建一个分支,该分支重新加入主管道。

    MapWhen:根据给定谓词的结果分支请求管道。

    换句话说,MapWhen 在委托返回 true 时停止执行管道的其余部分。

    【讨论】:

    • 是的,它奏效了。我什至不知道 UseWhen 存在,谢谢!我很困惑。
    • @MistaJoe 很酷,那么请accept this answer
    • 已接受,对 SO 还是有点陌生​​,抱歉!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    相关资源
    最近更新 更多