asp.net-core 使用ExceptionHandler中间件向客户端发送自定义JSON错误

示例

定义将代表您的自定义错误的类。

public class ErrorDto
{
   public int Code { get; set; }
   public string Message { get; set; }

   // 其他领域

   public override string ToString()
   {
      return JsonConvert.SerializeObject(this);
   }
}

然后将下一个ExceptionHandler中间件放入Configure方法。注意中间件的顺序很重要。

app.UseExceptionHandler(errorApp =>
    {
        errorApp.Run(async context =>
        {
            context.Response.StatusCode = 500; // 或其他状态 
            context.Response.ContentType = "application/json";

            var error = context.Features.Get<IExceptionHandlerFeature>();
            if (error != null)
            {
                var ex = error.Error;

                await context.Response.WriteAsync(new ErrorDto()
                {
                    Code = <your custom code based on Exception Type>,
                    Message =ex.Message// 或您的自定义消息
                    
                    ... // 其他自定义数据
                }.ToString(), Encoding.UTF8);
            }
        });
    });