Handling exception in asp.net core?

前端 未结 2 408
面向向阳花
面向向阳花 2021-02-03 23:35

I have asp.net core application. The implementation of configure method redirects the user to \"Error\" page when there is an exception ( in non Development environment)

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 00:07

    You should write your own middleware to handle custom exception handling. And make sure you add it towards the beginning (first if possible) of your middleware stack because exceptions that happen in middleware that is "earlier" in a stack will not be handled.

    Example:

    public class CustomExceptionMiddleware
    {
        private readonly RequestDelegate _next;
    
        public CustomExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
            try 
            {
                await _next.Invoke(context);
            } 
            catch (Exception e) 
            {
                // Handle exception
            }
        }
    }
    

提交回复
热议问题