中间件未向 API 请求返回错误详细信息

Middleware not returning error details to API request

我在 asp.net 核心中有一个 API 项目,我有一个处理 JWT 身份验证的中间件。

这是验证令牌的方法

private void attachAccountToContext(HttpContext context, string token)
        {
            try
            {
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                byte[] encodedKey = Encoding.ASCII.GetBytes(_configuration["JWTSecretKey"]);
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey = new SymmetricSecurityKey(encodedKey),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);
            }
            catch (Exception ex)
            {
                throw new HttpRequestException(ex.Message);
            }

如果令牌过期,我会在控制台和 catch 语句中收到一条消息,但是当我从 Postman 发出请求时,在发布项目后,它 returns 错误 500 否不管我 throw.

我想return把错误信息发给客户端,但是我不知道怎么把它传出中间件

当您在开发环境中遇到错误时,将显示此错误。发布您的应用程序后,出于安全目的,这些纯错误消息应该对客户端隐藏。但是,您可以为客户端的 return 异常编写自己的异常中间件,没有安全风险,仅供参考;

    public class ExceptionMiddleware
    {
        private RequestDelegate _next;

        public ExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext);
            }
            catch (Exception e)
            {
                await HandleExceptionAsync(httpContext, e);
            }
        }

        private Task HandleExceptionAsync(HttpContext httpContext, Exception e)
        {
            httpContext.Response.ContentType = "application/json";
            httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            return httpContext.Response.WriteAsync(new ErrorDetails
            {
                StatusCode = httpContext.Response.StatusCode,
                Message = e.Message
            }.ToString());
        }
    }

然后你必须把它注册到IApplicationBuilder作为扩展方法

public static class ExceptionMiddlewareExtensions
{
     public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app)
     {
         app.UseMiddleware<ExceptionMiddleware>();
     }
}

然后您必须在 Startup.cs -> Configure 方法中将其注册为:

   app.ConfigureCustomExceptionMiddleware();

在这些配置之后,任何抛出的异常都将return连同消息和状态代码一起发送到客户端。