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 官宣新年祝福语简短