使用自定义中间件后无法再获取

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

我正在进入.NET Core,我在实现自定义中间件时遇到了一些问题。我有一个中间件应该检查​​标头是否有一个名为“用户密钥”的字段。如果没有,则返回400 ERROR。如果它有它,它应该给我请求的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个回答
2
投票

你的中间件很好,但是你需要使用UseWhen扩展方法而不是MapWhen来注册它。

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

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

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

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