使用自定义中间件后无法再获取
Can't GET any more after using custom middleware
我正在学习 .NET Core,但在实现自定义中间件时遇到了一些问题。我有一个中间件应该检查 headers 是否有一个名为 "user-key" 的字段。如果不是,那么它 returns 一个 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");
});
}
如果您需要更多信息,请告诉我。提前致谢!
你的中间件很好,但你需要使用 UseWhen
扩展方法而不是 MapWhen
来注册它。
UseWhen
: Conditionally creates a branch in the request pipeline that is rejoined to the main pipeline.
MapWhen
: Branches the request pipeline based on the result of the given predicate.
换句话说,当委托 returns 为真时,MapWhen
停止执行管道的其余部分。
我正在学习 .NET Core,但在实现自定义中间件时遇到了一些问题。我有一个中间件应该检查 headers 是否有一个名为 "user-key" 的字段。如果不是,那么它 returns 一个 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");
});
}
如果您需要更多信息,请告诉我。提前致谢!
你的中间件很好,但你需要使用 UseWhen
扩展方法而不是 MapWhen
来注册它。
UseWhen
: Conditionally creates a branch in the request pipeline that is rejoined to the main pipeline.
MapWhen
: Branches the request pipeline based on the result of the given predicate.
换句话说,当委托 returns 为真时,MapWhen
停止执行管道的其余部分。