【问题标题】:Middleware not returning error details to API request中间件未向 API 请求返回错误详细信息
【发布时间】:2022-01-28 23:22:00
【问题描述】:

我在 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 发出请求时,在发布项目后,无论我使用什么 throw,它都会返回错误 500。

我想将错误消息返回给客户端,但我不知道如何将其传递给中间件

【问题讨论】:

    标签: c# asp.net-core error-handling jwt


    【解决方案1】:

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

        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 -&gt; Configure 方法中注册它为:

       app.ConfigureCustomExceptionMiddleware();
    

    在这些配置之后,任何抛出的异常都将返回到客户端,并带有消息和状态码。

    【讨论】:

    • 谢谢,我会尽快尝试的,再做一件事。我必须在 JWT 之前或之后 configure 这个中间件吗?我遇到了配置管道问题
    • 成功了,如果将来有人需要它:在configure方法中,必须在JWT中间件之前添加异常中间件
    猜你喜欢
    • 2016-11-27
    • 1970-01-01
    • 2016-12-07
    • 2019-11-08
    • 2017-03-17
    • 2016-10-29
    • 2012-03-20
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多