username@email.com
2025-04-18 0fbf7c551ba932e7c8bfdb1086bd4ef7acc90a9c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace zhengcaioa.Model
{
    public class HttpGlobalExceptionFilter : ExceptionFilterAttribute
    {
        private readonly ILogger<HttpGlobalExceptionFilter> _logger;
        public HttpGlobalExceptionFilter(ILogger<HttpGlobalExceptionFilter> logger)
        {
            _logger = logger;
        }
 
        public override void OnException(ExceptionContext context)
        {
 
            var actionName = context.HttpContext.Request.RouteValues["controller"] + "/" + context.HttpContext.Request.RouteValues["action"];
            _logger.LogError($"--------{actionName} Error Begin--------");
            _logger.LogError($"  Error Detail:" + context.Exception.Message);
            //拦截处理
            if (!context.ExceptionHandled)
            {
                ContentResult Content = new ContentResult();
                Content.Content = GetRestContent(context.Exception.Message);
                Content.ContentType = "text/html";
 
                context.Result = Content;
                context.ExceptionHandled = true;
            }
            _logger.LogError($"--------{actionName} Error End--------");
        }
 
 
        public static string GetRestContent(string msg)
        {
            StringBuilder jsContent = new StringBuilder();
            jsContent.AppendLine("<script type=\"text/javascript\">                                      ");
            jsContent.AppendLine("  alert(\"" + msg + "\");                  ");
            jsContent.AppendLine("</script>                                                              ");
 
            return jsContent.ToString();
        }
    }
}