Exemplo n.º 1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="code"></param>
 /// <param name="t"></param>
 /// <param name="count"></param>
 public ResponseModel(ErrorCode code, T t, long count = 0)
 {
     if (t is string)
     {
         string str = t.ToString();
         if ((str.Contains("{") && str.Contains("}")) || (str.Contains("[") && str.Contains("]")))
         {
         }
         else
         {
             str = JsonSerializerHelper.Serialize(t);
         }
         Content = "{\"code\":" + (int)code + ",\"message\":\"" + code.ToString() + "\",\"result\":" + str + ",\"count\":" + count + "}";
     }
     else
     {
         Content = "{\"code\":" + (int)code + ",\"message\":\"" + code.ToString() + "\",\"result\":" + JsonSerializerHelper.Serialize(t) + ",\"count\":" + count + "}";
     }
     ContentEncoding = Encoding.UTF8;
     ContentType     = "application/json";
 }
        /// <summary>
        /// 获取from列表
        /// </summary>
        /// <returns></returns>
        public ServiceModel <List <FromCountModel> > GetFromList()
        {
            var result = requestHelper.Get(baseUrl + "/log/getfromlist", null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <FromCountModel> > >(result));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            var actionDescriptor = (ControllerActionDescriptor)context.ActionDescriptor;
            IEnumerable <CustomAttributeData> methodAttributes     = actionDescriptor.MethodInfo.CustomAttributes;
            IEnumerable <CustomAttributeData> controllerAttributes = actionDescriptor.ControllerTypeInfo.CustomAttributes;
            //是否记录日志标记
            bool isLog = true;

            foreach (CustomAttributeData item in controllerAttributes)
            {
                if (item.AttributeType.Name == "NoneLogRecordAttribute")
                {
                    isLog = false;
                }
                if (item.AttributeType.Name == "LogRecordAttribute")
                {
                    isLog = true;
                }
            }
            foreach (CustomAttributeData c in methodAttributes)
            {
                if (c.AttributeType.Name == "NoneLogRecordAttribute")
                {
                    isLog = false;
                }
                if (c.AttributeType.Name == "LogRecordAttribute")
                {
                    isLog = true;
                }
            }
            if (!isLog)
            {
                return;
            }
            MessageCenterService messageService = new MessageCenterService(BaseUrl);
            HttpRequest          request        = context.HttpContext.Request;
            //日志调用api
            var to = AppSettings.GetApplicationUrl(request).ReplaceHttpPrefix().TrimEnd('/').ToLower();
            //不使用路由中的字符串因为用户可能输入大小写,不利于统计
            var controller = actionDescriptor.ControllerName;
            var action     = actionDescriptor.ActionName;
            //路由,解决 home/index/1 后面的1无法记录
            var route = "";

            foreach (var item in context.RouteData.Values)
            {
                var value = item.Value.ToString().ToLower();
                if (value == controller.ToLower() || value == action.ToLower())
                {
                    continue;
                }
                route += item.Key + "=" + item.Value.ToString() + "&";
            }
            route = route.TrimEnd('&');
            var querystring = "*";

            if (RecordQuerystring)
            {
                querystring = request.QueryString.Value;
            }
            var requestContent = "*";

            if (RecordRequestContent)
            {
                var hasForm = request.HasFormContentType;
                if (hasForm && request.Form.Files.Count > 0)
                {
                    List <string> fileNames = new List <string>();
                    for (var i = 0; i < request.Form.Files.Count; i++)
                    {
                        fileNames.Add(request.Form.Files[i].FileName);
                    }
                    requestContent = string.Join(",", fileNames);
                }
                else
                {
                    request.Body.Seek(0, SeekOrigin.Begin);
                    var reader = new StreamReader(request.Body);
                    requestContent = reader.ReadToEndAsync().Result.Replace("\n", "").Replace("\t", "").Replace("\r", "");
                    request.Body.Seek(0, SeekOrigin.Begin);
                }
            }
            var responseContent = "*";

            if (RecordResponseContent)
            {
                var result = context.Result;
                if (result is JsonResult)
                {
                    responseContent = JsonSerializerHelper.Serialize(((JsonResult)result).Value);
                }
                if (result is ViewResult)
                {
                    responseContent = "ViewResult";
                }
                if (result is ContentResult)
                {
                    responseContent = ((ContentResult)result).Content;
                }
                if (result is StatusCodeResult)
                {
                    responseContent = ((StatusCodeResult)result).StatusCode + "-";
                }
                if (result is FileResult)
                {
                    responseContent = ((FileResult)result).FileDownloadName;
                }
                if (result is ObjectResult)
                {
                    responseContent = JsonSerializerHelper.Serialize(((ObjectResult)result).Value);
                }
                if (result is EmptyResult)
                {
                    responseContent = "";
                }
                if (result is RedirectResult)
                {
                    responseContent = "redirect:" + ((RedirectResult)result).Url;
                }
                if (result is RedirectToRouteResult)
                {
                    responseContent = "route:" + ((RedirectToRouteResult)result).RouteName;
                }
            }
            string userId = "", userName = "", from = "";;
            string authorization = JwtManager.GetAuthorization(request, CookieKey);

            if (!authorization.IsNullOrEmpty())
            {
                ClaimsPrincipal claimsPrincipal = JwtManager.ParseAuthorization(authorization, SecretKey, request.HttpContext);
                UserData        userData        = JwtManager.ParseUserData(claimsPrincipal);
                userId   = userData.UserId;
                userName = userData.UserName;
                from     = userData.From.ReplaceHttpPrefix().TrimEnd('/').ToLower();
            }
            string userHost  = request.HttpContext.Connection.RemoteIpAddress.ToString();
            string userAgent = request.Headers["User-Agent"];
            var    time      = DateTime.UtcNow.MillisecondTimeStamp() - (long)context.HttpContext.Items["log_time_start"];
            bool   exception = context.Exception != null;

            messageService.InsertLog(from, to, controller, action, route, querystring, requestContent, responseContent, userId, userName, userHost, userAgent, time, exception);
        }
        /// <summary>
        /// 通过id获取日志详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ServiceModel <LogModel> GetById(string id)
        {
            var result = requestHelper.Get(baseUrl + "/log/getbyid/" + id, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <LogModel> >(result));
        }
        /// <summary>
        /// 获取最新的日志,按天统计
        /// </summary>
        /// <param name="last">最近多少天</param>
        /// <returns></returns>
        public ServiceModel <List <LogOpCountModel> > GetOpRecordByDay(int last = 30)
        {
            var result = requestHelper.Get(baseUrl + "/log/recordbyday?last=" + last, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <LogOpCountModel> > >(result));
        }
        /// <summary>
        /// 获取from中action列表
        /// </summary>
        /// <param name="to"></param>
        /// <param name="controllerName"></param>
        /// <returns></returns>
        public ServiceModel <List <ActionCountModel> > GetActionsByController(string to, string controllerName)
        {
            var result = requestHelper.Get(baseUrl + "/log/getactionsbycontroller?to=" + to + "&controllerName=" + controllerName, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <ActionCountModel> > >(result));
        }
        /// <summary>
        /// 统计昨天,上月,全部日志
        /// </summary>
        /// <returns></returns>
        public ServiceModel <OperationsCountModel> GetOperations()
        {
            var result = requestHelper.Get(baseUrl + "/log/getoperations", null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <OperationsCountModel> >(result));
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ServiceModel <List <RoleItem> > GetRoleList(string filter = "", int pageIndex = 1, int pageSize = 10)
        {
            string roles = requestHelper.Get(RemoteUrl + "/role/getlist?filter=" + filter + "&pageIndex=" + pageIndex + "&pageSize=" + pageSize, headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <RoleItem> > >(roles));
        }
        /// <summary>
        /// 获取to中Controller列表
        /// </summary>
        /// <param name="to"></param>
        /// <returns></returns>
        public ServiceModel <List <ControllerCountModel> > GetControllersByTo(string to)
        {
            var result = requestHelper.Get(baseUrl + "/log/getcontrollersbyto?to=" + to, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <ControllerCountModel> > >(result));
        }
        /// <summary>
        /// 获取指定department列表
        /// </summary>
        /// <param name="companyCode"></param>
        /// <returns></returns>
        public ServiceModel <List <DepartmentItem> > GetAllDepartment(string companyCode)
        {
            string departments = requestHelper.Get(RemoteUrl + "/department/getDepartments?companyCode=" + companyCode, headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <DepartmentItem> > >(departments));
        }
        /// <summary>
        /// 获取user列表
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="companyCode"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ServiceModel <List <UserItem> > GetUserList(string companyCode = "", string filter = "", int pageIndex = 1, int pageSize = 10)
        {
            string users = requestHelper.Get(RemoteUrl + "/user/getBasic?companyCode=" + companyCode + "&filter=" + filter + "&orderField=UserName&orderType=asc&pageIndex=" + pageIndex + "&pageSize=" + pageSize, headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <UserItem> > >(users));
        }
        /// <summary>
        /// 获取所有company
        /// </summary>
        /// <returns></returns>
        public ServiceModel <List <CompanyItem> > GetAllCompany()
        {
            string companys = requestHelper.Get(RemoteUrl + "/company/getall", headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <CompanyItem> > >(companys));
        }
        /// <summary>
        /// 替换权限项
        /// </summary>
        /// <param name="origin">项目标记</param>
        /// <param name="names">权限列表</param>
        /// <returns></returns>
        public ServiceModel <string> ReplacePermissions(string origin, IEnumerable <string> names)
        {
            string result = requestHelper.Post(RemoteUrl + "/permission/add", new { Origin = origin, Names = names }, headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <string> >(result));
        }
        /// <summary>
        /// 获取user详情
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ServiceModel <UserDetail> GetUserDetail(string userId)
        {
            string user = requestHelper.Get(RemoteUrl + "/user/getByUserId?userId=" + userId, headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <UserDetail> >(user));
        }
        /// <summary>
        /// 添加调度任务
        /// </summary>
        /// <param name="machineName"></param>
        /// <param name="schedulingId"></param>
        /// <param name="triggerId"></param>
        /// <param name="schedulingState"></param>
        /// <returns></returns>
        public ServiceModel <string> InsertTaskScheduling(string machineName, int schedulingId, int triggerId, int schedulingState)
        {
            var result = requestHelper.Post(baseUrl.TrimEnd('/') + "/TaskScheduling/insert", new { machineName, schedulingId, triggerId, schedulingState }, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <string> >(result));
        }
        /// <summary>
        /// 添加转换任务
        /// </summary>
        /// <param name="machineName">发往那个机器</param>
        /// <param name="collectionName"></param>
        /// <param name="collectionId"></param>
        /// <returns></returns>
        public ServiceModel <string> InsertConvertTask(string machineName, string collectionName, string collectionId)
        {
            var result = requestHelper.Post(baseUrl.TrimEnd('/') + "/filetask/insert", new { machineName, collectionName, collectionId }, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <string> >(result));
        }