Exemplo n.º 1
0
        public IActionResult Index()
        {
            var viewModel = new  IpViewModel {
                IpAdress = _ipAddressService.GetRequestIp()
            };

            return(View(viewModel));
        }
Exemplo n.º 2
0
        public bool TryGetFromCache(string ip, out IpViewModel model)
        {
            model = null;

            if (_Cache.Value.TryGetValue(ip, out IpViewModel cacheModel))
            {
                model = cacheModel;
                model.ProviderOrCacheUsed = "Cache";
                return(true);
            }

            return(false);
        }
Exemplo n.º 3
0
        public JsonResult BlockIpAddress(IpViewModel model)
        {
            if (!string.IsNullOrEmpty(model.Ip))
            {
                if (model.Action == "Block")
                {
                    unitOfWork.BlockedIpRepository.BlockIpAddress(model.Ip);
                }
                else
                {
                    unitOfWork.BlockedIpRepository.UnBlockIpAddress(model.Ip);
                }
            }

            return(Json("Success", JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 4
0
        public async Task <IpViewModel> TryGetIpViewModel(string ip)
        {
            IpViewModel model;

            // get the url and api key from the web config file
            string firstPartUrl = System.Configuration.ConfigurationManager.AppSettings["ipStackUrl"];
            string apiKey       = System.Configuration.ConfigurationManager.AppSettings["ipStackApiKey"];

            // create the url
            string finalUrl = firstPartUrl + ip + "?access_key=" + apiKey;

            // get the result from the ipStack api
            string jsonResult;

            using (var client = new HttpClient())
            {
                Uri uri = new Uri(finalUrl);
                client.Timeout = TimeSpan.FromMilliseconds(2000);

                HttpResponseMessage response = await client.GetAsync(uri);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    throw new HttpStatusCodeNotOKException();
                }

                jsonResult = await response.Content.ReadAsStringAsync();

                // convert json object to c# annonymous object
                dynamic data = Json.Decode(jsonResult);
                if (data.country_name == null || data.country_name == "UNKOWN" || data.country_name == "Reserved")
                {
                    throw new IpIsValidButDoesNotCorrespondToAnyCountryException();
                }

                // crete the model to return
                model = new IpViewModel
                {
                    IP             = ip,
                    TwoLettersCode = data.country_code,
                    Country        = data.country_name
                };

                return(model);
            }
        }
Exemplo n.º 5
0
        public async Task <IpViewModel> TryGetIpViewModel(string ip)
        {
            IpViewModel model;

            // get the ip2c url from web config file
            string firstPartUrl = System.Configuration.ConfigurationManager.AppSettings["ip2cUrl"];

            // create the url
            string finalUrl = firstPartUrl + ip;

            // get the result from ip2c api
            string textResult;

            using (var client = new HttpClient())
            {
                Uri uri = new Uri(finalUrl);
                client.Timeout = TimeSpan.FromMilliseconds(1000);

                HttpResponseMessage response = await client.GetAsync(uri);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    throw new HttpStatusCodeNotOKException();
                }

                textResult = await response.Content.ReadAsStringAsync();

                if (textResult.Split(';')[0] == "0")
                {
                    throw new IpIsValidButDoesNotCorrespondToAnyCountryException();
                }
            }

            // split it to get the actual data
            string[] splitTextResult = textResult.Split(';');

            // create the model to return
            model = new IpViewModel
            {
                IP             = ip,
                Country        = splitTextResult[3],
                TwoLettersCode = splitTextResult[1]
            };

            return(model);
        }
Exemplo n.º 6
0
        public void AddToCache(IpViewModel model)
        {
            model.DateInserted = DateTime.Now;

            _Cache.Value.TryAdd(model.IP, model);
        }
Exemplo n.º 7
0
        public async Task <ActionResult> Get(IpViewModel inputModel)
        {
            if (ModelState.IsValid)
            {
                IpCache cache = new IpCache();

                IpViewModel ipViewModel;

                if (cache.TryGetFromCache(inputModel.IP, out IpViewModel model))
                {
                    ipViewModel = model;

                    return(View("Index", ipViewModel));
                }


                //try ip2c Service
                int tries = 0;

                while (tries < 3)
                {
                    try
                    {
                        IService ip2cService = new Ip2cService();

                        ipViewModel = await ip2cService.TryGetIpViewModel(inputModel.IP);

                        ipViewModel.ProviderOrCacheUsed = "Ip2c";

                        return(View("Index", ipViewModel));
                    }
                    catch (TaskCanceledException)
                    {
                        tries += 1;
                    }
                    catch (HttpStatusCodeNotOKException)
                    {
                        tries += 1;
                    }
                    catch (IpIsValidButDoesNotCorrespondToAnyCountryException)
                    {
                        ViewData["ErrorMessage"] = "This Ip is valid but does not correspond to any country";
                        return(View("Index"));
                    }
                    catch (Exception)
                    {
                        tries += 1;
                    }
                }

                // try ipStack Service
                tries = 0;

                while (tries < 3)
                {
                    try
                    {
                        IService ipStackService = new IpStackService();

                        ipViewModel = await ipStackService.TryGetIpViewModel(inputModel.IP);

                        ipViewModel.ProviderOrCacheUsed = "IpStack";

                        return(View("Index", ipViewModel));
                    }
                    catch (TaskCanceledException)
                    {
                        tries += 1;
                    }
                    catch (HttpStatusCodeNotOKException)
                    {
                        tries += 1;
                    }
                    catch (IpIsValidButDoesNotCorrespondToAnyCountryException)
                    {
                        ViewData["ErrorMessage"] = "This Ip is valid but does not correspond to any country";
                        return(View("Index"));
                    }
                    catch (Exception)
                    {
                        tries += 1;
                    }
                }

                // this far all have failed so return null model
                ViewData["ErrorMessage"] = "Services Failed";
                return(View("Index"));
            }
            else
            {
                return(View("Index"));
            }
        }