zhaojs
2023-09-27 74098f1401afe40f961d1d167bb18dd0a71c4d59
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
using CommonUtil;
using EasyCaching.Core;
using Link.Api.Attributes;
using Link.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Text;
 
namespace Link.Api.Filters
{
    /// <summary>
    /// Action过滤器
    /// </summary>
    public class ActionFilter : IActionFilter
    {
        private const string JSON_RPC = "2.0";
        /// <summary>
        /// 缓存容器
        /// </summary>
        private readonly IEasyCachingProvider _provider;
 
        /// <summary>
        /// 构造函数
        /// </summary>
        public ActionFilter(IEasyCachingProvider easyCachingProvider)
        {
            this._provider = easyCachingProvider;
        }
 
        /// <summary>
        /// Action执行前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var controllerTypeInfo = ((ControllerBase)context.Controller).ControllerContext.ActionDescriptor.ControllerTypeInfo;
 
//#if DEBUG
//            var actionMetadata = new EndpointMetadataCollection(context.ActionDescriptor.EndpointMetadata);
//            var actionAttributes = actionMetadata.GetMetadata<IApiResponseMetadataProvider>();
 
//            //未标识返回类型
//            if (actionAttributes.IsNull())
//            {
//                LogUtil.Trace($"------------未标识返回类型----------------");
//                context.Result = new OkObjectResult(new
//                {
//                    jsonrpc = JSON_RPC,
//                    id = Guid.NewGuid().ToString(),
//                    error = new
//                    {
//                        code = (int)TopResultEnum.UndefinedResponseType,
//                        message = TopResultEnum.UndefinedResponseType.GetDescription()
//                    }
//                });
//                return;
//            }
//            LogUtil.Trace($"------------校验标识返回类型:true----------------");
 
//            //未继承基类返回
//            if (controllerTypeInfo.BaseType != typeof(Controllers.BaseController))
//            {
//                LogUtil.Trace($"------------未继承基类返回----------------");
//                context.Result = new OkObjectResult(new
//                {
//                    jsonrpc = JSON_RPC,
//                    id = Guid.NewGuid().ToString(),
//                    error = new
//                    {
//                        code = (int)TopResultEnum.ErrorBaseType,
//                        message = TopResultEnum.ErrorBaseType.GetDescription()
//                    }
//                });
//                return;
//            }
//            LogUtil.Trace($"------------校验继承基类返回:true----------------");
 
//            //未使用统一命名空间
//            string nameSpace = controllerTypeInfo.Namespace;
//            if (nameSpace != Constants.API_LIBRARY_NAMESPACE)
//            {
//                LogUtil.Trace($"------------未使用统一命名空间----------------");
//                context.Result = new OkObjectResult(new
//                {
//                    jsonrpc = JSON_RPC,
//                    id = Guid.NewGuid().ToString(),
//                    error = new
//                    {
//                        code = (int)TopResultEnum.ErrorNameSpace,
//                        message = TopResultEnum.ErrorNameSpace.GetDescription()
//                    }
//                });
//                return;
//            }
//            LogUtil.Trace($"------------校验使用统一命名空间:true----------------");
//#endif
            var req = context.HttpContext.Request;
 
            string method = req.Method.ToUpper();
            //非法的请求类型
            if (method != TopConstants.HTTP_GET && method != TopConstants.HTTP_POST)
            {
                LogUtil.Trace($"------------非法的请求类型----------------");
                context.Result = new OkObjectResult(new
                {
                    jsonrpc = JSON_RPC,
                    id = Guid.NewGuid().ToString(),
                    error = new
                    {
                        code = (int)TopResultEnum.HttpMehtodError,
                        message = TopResultEnum.HttpMehtodError.GetDescription()
                    }
                });
                return;
            }
 
            //参数校验
            if (!context.ModelState.IsValid)
            {
                LogUtil.Trace($"------------参数校验不通过----------------");
                string errorMsg = context.ModelState.Values.SelectMany(e => e.Errors).Select(e => e.ErrorMessage).FirstOrDefault();
                context.Result = new OkObjectResult(new
                {
                    jsonrpc = JSON_RPC,
                    id = Guid.NewGuid().ToString(),
                    error = new
                    {
                        code = (int)TopResultEnum.ErrorGeneral,
                        message = errorMsg
                    }
                });
                return;
            }
            context.HttpContext.Items.Add(TopConstants.LOG_KEY, DateTime.Now.ToMillisecondString());
        }
 
 
        /// <summary>
        /// Action执行后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            try
            {
//#if !DEBUG
//                var actionMetadata = new EndpointMetadataCollection(context.ActionDescriptor.EndpointMetadata);
//                var flushCacheAttributes = actionMetadata.GetMetadata<FlushCacheAttribute>();
//                if (!flushCacheAttributes.IsNull() && flushCacheAttributes.IsFlush)
//                {
//                    _provider.Flush();
//                }
//                var request = context.HttpContext.Request;
//                string traceId = context.HttpContext.TraceIdentifier;
 
//                //入参
//                request.EnableRewind();
//                request.Body.Position = 0;
//                string requestValues = TopUtil.Stream2String(request.Body);
 
//                //出参
//                string responseMsg = string.Empty;
 
//                if (!context.Result.IsNull() && context.Result.GetType() == typeof(ObjectResult))
//                {
//                    responseMsg = JsonConvert.SerializeObject(((ObjectResult)context.Result).Value);
//                }
 
//                StringBuilder sb = new StringBuilder();
 
//                sb.AppendLine($"请求ID:{traceId}");
//                sb.AppendLine($"请求URL:{request.Path}");
//                sb.AppendLine($"请求是否HTTPS:{request.IsHttps}");
//                sb.AppendLine($"请求Header明细:{JsonConvert.SerializeObject(request.Headers)}");
 
//                if (request.Headers.ContainsKey("Content-Type"))
//                    sb.AppendLine($"请求报文类型Content-Type:{request.Headers["Content-Type"]}");
//                if (request.Headers.ContainsKey("Accept"))
//                    sb.AppendLine($"请求接收报文类型Accept:{request.Headers["Accept"]}");
//                if (request.Headers.ContainsKey("Cookie"))
//                    sb.AppendLine($"请求携带Cookie:{request.Headers["Cookie"]}");
//                if (request.Headers.ContainsKey("Host"))
//                    sb.AppendLine($"请求Host:{request.Headers["Host"]}");
//                if (request.Headers.ContainsKey("Referer"))
//                    sb.AppendLine($"请求Host:{request.Headers["Referer"]}");
//                if (request.Headers.ContainsKey("User-Agent"))
//                    sb.AppendLine($"请求User-Agent:{request.Headers["User-Agent"]}");
//                if (request.Headers.ContainsKey("Origin"))
//                    sb.AppendLine($"请求Origin:{request.Headers["Origin"]}");
//                if (request.Headers.ContainsKey("Content-Length"))
//                    sb.AppendLine($"请求入参报文长度Content-Length:{request.Headers["Content-Length"]}");
 
//                sb.AppendLine($"请求入参:{requestValues}");
//                sb.AppendLine($"请求入参是否通过验证:{context.ModelState.IsValid}");
//                sb.AppendLine($"响应HTTP状态码:{context.HttpContext.Response.StatusCode}");
//                sb.AppendLine($"响应出参:{responseMsg}");
 
//                if (context.HttpContext.Items.ContainsKey(TopConstants.LOG_KEY))
//                    sb.AppendLine($"请求开始时间:{context.HttpContext.Items[TopConstants.LOG_KEY]}");
 
//                sb.AppendLine($"响应结束时间:{DateTime.Now.ToMillisecondString()}");
 
//                LogUtil.Info(sb.ToString(), "访问日志");
//#endif
            }
            catch (Exception e)
            {
                LogUtil.Error(e, "访问日志");
            }
        }
    }
}