This article mainly introduces the ExceptionFilter filter of the asp.net core MVC global filter in detail. It has a certain reference value. Interested friends can refer to it.
This series of classes will Will explain the use of the built-in global filter in asp.net core MVC, which will be divided into the following chapters
asp.net core MVC filter ExceptionFilter filter (1)
asp.net core MVC filter's ActionFilter filter (2)
asp.net core MVC filter's ResultFilter filter (3)
asp.net core MVC filter's ResourceFilter filter (4) )
AuthorizationFilter filter of asp.net core MVC filter (5)
Introduction
Exception filter, as the name suggests, is when the program occurs Filter to use on exceptions. Used to handle uncaught exceptions in the system.
Implementing a custom exception filter
Customizing a global exception filter requires implementing the IExceptionFilter interface
##
public class HttpGlobalExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { throw new NotImplementedException(); } }
/// <summary> /// 全局异常过滤器 /// </summary> public class HttpGlobalExceptionFilter : IExceptionFilter { readonly ILoggerFactory _loggerFactory; readonly IHostingEnvironment _env; public HttpGlobalExceptionFilter(ILoggerFactory loggerFactory, IHostingEnvironment env) { _loggerFactory = loggerFactory; _env = env; } public void OnException(ExceptionContext context) { var logger = _loggerFactory.CreateLogger(context.Exception.TargetSite.ReflectedType); logger.LogError(new EventId(context.Exception.HResult), context.Exception, context.Exception.Message); var json = new ErrorResponse("未知错误,请重试"); if (_env.IsDevelopment()) json.DeveloperMessage = context.Exception; context.Result = new ApplicationErrorResult(json); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.ExceptionHandled = true; } public class ApplicationErrorResult : ObjectResult { public ApplicationErrorResult(object value) : base(value) { StatusCode = (int)HttpStatusCode.InternalServerError; } } public class ErrorResponse { public ErrorResponse(string msg) { Message = msg; } public string Message { get; set; } public object DeveloperMessage { get; set; } }
services.AddMvc(options => { options.Filters.Add<HttpGlobalExceptionFilter>(); });
Test
Throw an exception in the requestThe above is the detailed content of ExceptionFilter filter in asp.net. For more information, please follow other related articles on the PHP Chinese website!