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);
}
});
});
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下