【发布时间】: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