[英]Customize Asp.NET Core Identity Unauthorized Response Type and Statuscode
[英]ASP.NET Core HttpContext.Response.StatusCode is 200 when exception
我有一个抛出异常的端点。
[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。为什么?
然而,Postman 告诉我我的请求失败了,我看到了错误本身,因此一切看起来都很正常。 尽管日志包含 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();
});
}
}
}
如果你想捕获异常,你需要使用特定的中间件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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.