我有一個拋出例外的端點。
[ApiController]
[Route("api")]
public class LegacyController : ControllerBase
{
[HttpPost("endpoint")]
public async Task<ActionResult<IEnumerable<Entitty>>> GetAll()
{
throw new Exception();
return Ok(t.ToList());
}
}
我有自定義的 Http 日志過濾器,看起來像這樣
using Microsoft.AspNetCore.Http;
namespace Client.API.Extensions
{
public class HttpLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public HttpLoggingMiddleware(RequestDelegate next, ILogger<HttpLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
finally
{
_logger.LogInformation(
"Request {method} {url} => {statusCode}",
context.Request?.Method,
context.Request?.Path.Value,
context.Response?.StatusCode);
}
}
}
}
當我呼叫這個端點時,context.Response?.StatusCode 是 200。為什么?
但是,郵遞員告訴我我的請求失敗了,我看到了錯誤本身,因此一切看起來都很正常。雖然日志包含 200 條狀態代碼訊息,而不是 500 條。
編輯:這是我的啟動(洗掉了一些部分)。
namespace Client.API
{
public class Startup
{
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseHttpsRedirection();
app.UsePathBase(new PathString(basePath));
app.UseRouting();
app.UseMiddleware<HttpLoggingMiddleware>();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
uj5u.com熱心網友回復:
如果你想捕獲例外,你需要使用特定的中間件app.UseExceptionHandler();--,所以我首先使用這個中間件來設定日志。
代碼是:
app.UseExceptionHandler(
appErr =>
{
appErr.Run(
async context =>
{
logger.LogInformation(
"Request {method} {url} => {statusCode}",
context.Request?.Method,
context.Request?.Path.Value,
context.Response?.StatusCode);
});
});
但是有一個問題,這個中間件只能捕獲例外,所以當回應碼不是500時,請求不會進入這個中間件。
最后我改變了一個方法,我try/catch用來捕獲例外并StatusCode自己設定它并成功。代碼如下:
public class HttpLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<HttpLoggingMiddleware> _logger;
public HttpLoggingMiddleware(RequestDelegate next,ILogger<HttpLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception)
{
//catch the Exception and set the StatusCode
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
finally
{
_logger.LogInformation(
"Request {method} {url} => {statusCode}",
context.Request?.Method,
context.Request?.Path.Value,
context.Response?.StatusCode);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/431755.html
標籤:C# asp.net 核心 .net-core asp.net-core-webapi
