mic*_*cer 1 c# .net-core asp.net-core asp.net-core-3.1
当中间件出现问题时,我想向用户发送错误的请求代码。
我的Startup.cs看起来像这样:
// configure method
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseMiddleware<RequestMiddleware>();
app.UseMiddleware<SecondRequestMiddleware>();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Run Code Online (Sandbox Code Playgroud)
我的中间件如下所示:
public class RequestMiddleware
{
private readonly RequestDelegate _next;
public RequestMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, IAuthInfoService authInfoService, IPowiadomieniaCacheService cacheService)
{
string jwt = context.Request.Headers["custom_header"];
if (string.IsNullOrEmpty(jwt))
{
// no jwt in headers so i want to return Unauthorized to user:
await ReturnErrorResponse(HttpContext context);
}
}
private Task ReturnErrorResponse(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Task.CompletedTask;
}
}
Run Code Online (Sandbox Code Playgroud)
但我仍然进入我的SecondRequestMiddleware。401 Stauts Code当标头中没有jwt(这就是我的RequestMiddleware检查)并停止处理此请求时,我想返回给用户。
如何验证中间件中的请求,如果条件通过,则向用户返回错误代码/响应?
小智 10
您可以修改中间件以短路请求,如下所示。哪里await context.Response.StartAsync();会开始回应,不会进一步进行。
public class RequestMiddleware
{
private readonly RequestDelegate _next;
public RequestMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, IAuthInfoService authInfoService, IPowiadomieniaCacheService cacheService)
{
string jwt = context.Request.Headers["custom_header"];
if (string.IsNullOrEmpty(jwt))
{
// no jwt in headers so i want to return Unauthorized to user:
await ReturnErrorResponse(HttpContext context);
}
else
{
await _next(context);
}
}
private async Task ReturnErrorResponse(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await context.Response.StartAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4049 次 |
| 最近记录: |