コード例 #1
0
        /// <summary>
        /// 在请求执行完后 记录请求的数据以及返回数据
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            object beginTime = null;

            if (actionExecutedContext.Request.Properties.TryGetValue(key, out beginTime))
            {
                var menuAction  = actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes <MenuAttribute>().OfType <MenuAttribute>().FirstOrDefault();
                var menuAction1 = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes <MenuAttribute>().OfType <MenuAttribute>().FirstOrDefault();

                HttpRequestBase request = CurrentHttpContext.Instance().Request;
                DateTime        time    = DateTime.FromBinary(Convert.ToInt64(beginTime));
                //var accessChannelInfo = ConfigurationHelper.AccessChannelSetting; // load AccessChannel.xml

                SysOperationLog apiActionLog = new SysOperationLog();

                //提取Identity
                var id = CurrentHttpContext.Instance().User.Identity as ClaimsIdentity;
                if (id != null)
                {
                    int accessChannelId = 0;
                    int.TryParse(id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Actor)?.Value, out accessChannelId);

                    var appType = id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.System)?.Value;
                    var token   = id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Authentication)?.Value;
                    apiActionLog.SourceEquipment = appType;
                    apiActionLog.Token           = token;
                    var data = id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.UserData)?.Value;
                    if (data != null)
                    {
                        var user = JsonConvert.DeserializeObject <SysUser>(data);
                        if (user != null)
                        {
                            //获取用户token
                            apiActionLog.UserId = user.Id;
                        }
                    }
                }
                else
                {
                    apiActionLog.SourceEquipment = "未知";
                    //获取用户token
                    apiActionLog.UserId = 0;
                }

                //获取action名称
                apiActionLog.MethodAction = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
                //获取Controller 名称
                apiActionLog.FunctionController = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                //获取action开始执行的时间
                apiActionLog.ExecutionTime = time;
                //获取执行action的耗时
                apiActionLog.ExecutionDuration = (DateTime.Now - time).Milliseconds;
                apiActionLog.Navigator         = request.UserAgent;
                //获取访问的ip
                ExploreHelper eh = new ExploreHelper(request);

                apiActionLog.ClientIpAddress = eh.ClientIP;
                //客户端名称
                apiActionLog.ClientName = eh.ClientMachineName;
                //Url来源
                apiActionLog.UrlReferrer = request.UrlReferrer != null ? request.UrlReferrer.AbsoluteUri : "";
                //浏览器信息
                apiActionLog.BrowserInfo = request.Browser.Browser + " - " + request.Browser.Version + " - " + request.Browser.Type;
                //获取request提交的参数
                apiActionLog.Parameters = GetRequestValues(actionExecutedContext) + " " + GetRequestActionValues(actionExecutedContext);

                //获取response响应的结果
                //apiActionLog.Exception = GetResponseValues(actionExecutedContext);
                // "",JsonConvert.SerializeObject(actionExecutedContext.Response.RequestMessage);
                try
                {
                    apiActionLog.IPNum = (int)StringHelper.IPToInt(eh.ClientIP);
                }
                catch
                {
                    apiActionLog.IPNum = 0;
                }
                apiActionLog.Description = msg;

                apiActionLog.RequestUri = request.Url.AbsoluteUri;
                apiActionLog.Enabled    = 1;
                WriteLogService.WriteLogOperate(apiActionLog);
            }
            return(base.OnActionExecutedAsync(actionExecutedContext, cancellationToken));
        }
コード例 #2
0
ファイル: CorsHandler.cs プロジェクト: makepower/EB.ISCS
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            bool isCorsRequest = request.Headers.Contains(Origin);
            //是否是检测请求
            bool isPreflightRequest = request.Method == HttpMethod.Options;
            var  needApiLog         = false;

            Boolean.TryParse(ConfigurationManager.AppSettings["NeedApiLog"], out needApiLog);
            if (isCorsRequest)
            {
                if (isPreflightRequest)
                {
                    return(Task.Factory.StartNew <HttpResponseMessage>(() =>
                    {
                        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                        response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                        if (request.Headers.Contains(AccessControlRequestMethod))
                        {
                            string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
                            if (accessControlRequestMethod != null)
                            {
                                response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                            }
                        }

                        if (request.Headers.Contains(AccessControlRequestHeaders))
                        {
                            string requestedHeaders = request.Headers.GetValues(AccessControlRequestHeaders).FirstOrDefault();
                            if (!string.IsNullOrEmpty(requestedHeaders))
                            {
                                response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                            }
                        }
                        return response;
                    }, cancellationToken));
                }
                else
                {
                    //记录请求内容
                    if (request.Content != null)
                    {
                        if (needApiLog)
                        {
                            try
                            {
                                SysOperationLog model = new SysOperationLog();
                                model.MethodAction = request.RequestUri.LocalPath;
                                model.CustomData   = request.Content.ReadAsStringAsync().Result;
                                model.RequestType  = 0;

                                WriteLogService.WriteLogOperate(model);
                            }
                            catch (Exception e)
                            {
                                LogHelper.WriteErrorLog("记录请求内容出错:" + e.Message + e.StackTrace);
                            }
                        }
                    }
                    return(base.SendAsync(request, cancellationToken).ContinueWith <HttpResponseMessage>
                               (t =>
                    {
                        HttpResponseMessage resp = t.Result;
                        resp.Headers.Add(AccessControlAllowOrigin, "*");
                        resp.Headers.Add(AccessControlAllowHeaders, "Authorization");
                        if (needApiLog)
                        {
                            try
                            {
                                string res = t.Result.Content.ReadAsStringAsync().Result;

                                SysOperationLog model = new SysOperationLog();
                                model.MethodAction = request.RequestUri.LocalPath;
                                model.CustomData = res;
                                model.RequestType = 1;
                                WriteLogService.WriteLogOperate(model);
                            }
                            catch (Exception e)
                            {
                                LogHelper.WriteErrorLog("记录响应内容出错:" + request.RequestUri.LocalPath + e.Message + e.StackTrace);
                            }
                        }
                        return resp;
                    }));
                }
            }
            else
            {
                if (request.Content != null)
                {
                    if (needApiLog)
                    {
                        try
                        {
                            SysOperationLog model = new SysOperationLog();
                            model.MethodAction = request.RequestUri.LocalPath;
                            model.CustomData   = request.Content.ReadAsStringAsync().Result;
                            model.RequestType  = 0;
                            WriteLogService.WriteLogOperate(model);
                        }
                        catch (Exception e)
                        {
                            LogHelper.WriteErrorLog("记录请求内容出错:" + e.Message + e.StackTrace);
                        }
                    }
                }
                return(base.SendAsync(request, cancellationToken).ContinueWith <HttpResponseMessage>
                           (t =>
                {
                    HttpResponseMessage resp = t.Result;
                    resp.Headers.Add(AccessControlAllowOrigin, "*");
                    resp.Headers.Add(AccessControlAllowHeaders, "Authorization");
                    if (needApiLog)
                    {
                        try
                        {
                            string res = t.Result.Content.ReadAsStringAsync().Result;
                            SysOperationLog model = new SysOperationLog();
                            model.MethodAction = request.RequestUri.LocalPath;
                            model.CustomData = res;
                            model.RequestType = 1;
                            WriteLogService.WriteLogOperate(model);
                        }
                        catch (Exception e)
                        {
                            LogHelper.WriteErrorLog("记录响应内容出错:" + request.RequestUri.LocalPath + e.Message + e.StackTrace);
                        }
                    }
                    return resp;
                }));
            }
        }