public class MyException : Attribute, IExceptionFilter { private readonly ILogger<MyException> _logger; public MyException(ILogger<MyException> logger) { _logger = logger; } public void OnException(ExceptionContext context) { if (!context.ExceptionHandled) { //写入日志 _logger.LogError($"出错:{context.Exception.Message}"); //定义返回信息 var res = new { Code = 500, Message = "发生错误,请联系管理员" }; context.Result = new ContentResult { // 返回状态码设置为200,表示成功 StatusCode = StatusCodes.Status200OK, // 设置返回格式 //ContentType = "application/json;charset=utf-8", //Content = JsonConvert.SerializeObject(res) ContentType = "text/html;charset=utf-8", Content = $"<h2 style=‘color:red‘>发生错误 :{context.Exception.Message}</h2>" }; context.ExceptionHandled = true; } } }
services.AddControllersWithViews(options=> { options.Filters.Add(typeof(MyException)); });