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);
}
});
});
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短