Asp.net core MVC global filter ExceptionFilter (1), mvcexceptionfilter

Source: Internet
Author: User

Asp.net core MVC global filter ExceptionFilter (1), mvcexceptionfilter
This section describes how to use the built-in Global filter in asp.net core MVC.

ExceptionFilter of asp.net core MVC filter (1)

ActionFilter of asp.net core MVC filter (2)

ResultFilter of asp.net core MVC filter (III)

Asp.net core MVC filter ResourceFilter (4)

AuthorizationFilter for asp.net core MVC filter (5)

  

Introduction

The exception filter, as its name implies, is used when an exception occurs in the program. It is used to handle exceptions that are not captured by the system.

Implement a custom exception filter

To customize a global exception filter, you must implement the IExceptionFilter interface.

  

public class HttpGlobalExceptionFilter : IExceptionFilter    {        public void OnException(ExceptionContext context)        {            throw new NotImplementedException();        }    }

The IExceptionFilter interface requires the OnException method to be implemented. This method is triggered when no exception is caught by the system. The OnException method has an ExceptionContext exception context, which contains the specific exception information, HttpContext, and mvc routing information. Once an uncaptured exception occurs, the common practice is to use the log tool to record the detailed information of the exception to facilitate correction and debugging. Below is the implementation of logging.

  

/// <Summary> /// global exception filter /// </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 ("Unknown error, please try again"); if (_ env. isDevelopment () json. publish message = 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 receive Message {get; set ;}}
 
Register global Filter

The filter has been compiled, and you need to register it in asp.net core MVC. Find the system root directory Startup. cs file and modify ConfigureServices as follows:

 services.AddMvc(options =>            {                options.Filters.Add<HttpGlobalExceptionFilter>();            });
Test

Throw an exception in the request.

The log correctly captures the exception information.

The browser Returns Error 500 and a custom error message.

 

 

 

 

  

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.