.net核心-中间件don';我不能处理请求
我对.NETCore2中的中间件有问题。中间件不处理任何即将到来的请求。 我所实施的 KeyValidator中间件类:.net核心-中间件don';我不能处理请求,.net,asp.net-core,.net-core,.net,Asp.net Core,.net Core,我对.NETCore2中的中间件有问题。中间件不处理任何即将到来的请求。 我所实施的 KeyValidator中间件类: public class KeyValidatorMiddleware { private readonly RequestDelegate _next; public KeyValidatorMiddleware(RequestDelegate next) { _next = next; } public asyn
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>();
}
public void配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
附录UseCors(“我的政策”);
app.UseMiddleware();
}
什么都不起作用,为了让中间件工作,我缺少了什么?中间件的注册已被订购。因此,在MVC之前注册的任何内容都将在MVC之前运行
如果请求与MVC可以处理的URL匹配,MVC将处理该请求。在MVC之后注册的任何内容只有在MVC与URL不匹配时才会处理请求。您应该将
useMidleware
行移到更靠近顶部的位置,中间件按顺序运行,并且可能会在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");
}
public void配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseHsts();
}
app.UseMiddleware();
app.UseHttpsRedirection();
app.UseMvc();
附录UseCors(“我的政策”);
}
您在管道中的何处添加了UseMediddleware
行?你能给我们展示一个更完整的配置
方法吗?将UseMiddleware
行移到更靠近顶部的位置,中间件按顺序运行,可能会在MVC级别停止。OP:这是一个轻微的旁白,但你还需要重新考虑基于此信息的app.UseCors
的位置(和app.UseHttpsRedirection
实际上)。