Пример #1
0
        public async Task <IActionResult> CreateLog()
        {
            // get visitor geolocation info
            using (var reader = new DatabaseReader(_hostingEnvironment.ContentRootPath + "\\Data\\GeoLog\\GeoLite2-City.mmdb"))
            {
                // for  local dev test Determine the IP Address of the request
                // var ipAddress = "180.255.44.125";

                // get user/visitor ip address
                var ipAddress = HttpContext.Connection.RemoteIpAddress;

                // Get the city from the IP Address
                var log = reader.City(ipAddress);

                // ensure logging is done once a day only. Compares ip address and datelogged to current date
                // var IPDateExist = (_context.Logs.Where(g => g.IPAddress == ipAddress.ToString() && g.DateLogged.Date == DateTime.Now.Date).Count() > 0) ? true : false;
                var IPDateExist = _repo.IPDateExist(ipAddress.ToString());

                // when log does not exist, create or add log
                if (!IPDateExist)
                {
                    //save or log visitor info
                    Log geoLog = new Log();
                    geoLog.IPAddress  = ipAddress.ToString();
                    geoLog.City       = log.City.ToString();
                    geoLog.Country    = log.Country.ToString();
                    geoLog.Timezone   = log.Location.TimeZone;
                    geoLog.DateLogged = DateTime.Now;

                    var newLog = _mapper.Map <Log>(geoLog);
                    _repo.Add <Log>(newLog);

                    if (await _repo.SaveAll())
                    {
                        return(Ok(newLog));
                    }
                    throw new Exception("Log creation failed on save.");
                }

                return(Ok("ip already exist, no new log was created."));
            }
        }