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 入住酒店文案祝福语简短