zhaolei
7 days ago 921de2254ff5712a44ed8575ee8efe34252f6603
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
53
54
55
56
57
58
59
60
61
62
#if !NETSTANDARD2_0
using Microsoft.Extensions.Hosting;
#endif
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using System.Collections.Specialized;
using System.Net;
using System.Threading.Tasks;
 
namespace Microsoft.AspNetCore.Mvc.Filters
{
    /// <summary>
    /// 统一异常处理过滤器
    /// </summary>
    public class ExceptionFilter : IAsyncExceptionFilter
    {
#if !NETSTANDARD2_0
        private readonly IWebHostEnvironment _env;
#else
        private readonly IHostingEnvironment _env;
#endif
        private readonly ILogger<ExceptionFilter> _logger;
 
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="env"></param>
        /// <param name="logger"></param>
#if !NETSTANDARD2_0
        public ExceptionFilter(IWebHostEnvironment env, ILogger<ExceptionFilter> logger)
#else
        public ExceptionFilter(IHostingEnvironment env, ILogger<ExceptionFilter> logger)
#endif
        {
            _env = env;
            _logger = logger;
        }
 
        /// <summary>
        /// 异常发生时调用此方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (!_env.IsDevelopment())
            {
                var nv = new NameValueCollection
                {
                    ["ErrorPage"] = context.HttpContext.Request.Path,
                    ["UserIp"] = context.HttpContext.Connection.RemoteIpAddress.ToIPv4String(),
                    ["UserId"] = context.HttpContext.User.Identity.Name
                };
                _logger.Log(LogLevel.Error, new EventId(0), nv, context.Exception, (t, e) => string.Empty);
                context.ExceptionHandled = true;
                if (context.HttpContext.Request.Path.StartsWithSegments("/api")) context.Result = new JsonResult(new { message = context.Exception.Message, error = context.Exception.GetType().FullName });
                else context.Result = new StatusCodeResult(500);
            }
            return Task.CompletedTask;
        }
    }
}