Country visitors redirection with ASP.NET MVC and IP2Location Web Service

Country Visitors  Redirection with  ASP.NET MVC and  IP2Location Web Service

Intro

With the IP2Location Web Service, websites running ASP.NET MVC 5 can easily detect the visitor’s country and redirect them to other websites or other pages. In this article, we will be showing a barebone ASP.NET MVC 5 project using C# that demonstrates how to implement such a redirection. Our example will be redirecting visitors from the United States (US) and the United Kingdom (GB) to the IP2Location website.

If you are unfamiliar with MVC, you can go through some of the videos at the link below:

https://channel9.msdn.com/Series/Introduction-to-ASP-NET-MVC

 

Pre-requisites

  • Microsoft Visual Studio
  • .NET Framework 4.6.1 or later
  • An ASP.NET MVC project written in C#
  • IP2Location Web Service API key

 

Let’s get started

As everything hinges on the IP2Location Web Service, you must have an API key to call that. If you don’t have one, sign up for one at https://www.ip2location.com/web-service/ip2location. For testing purposes, you can just sign up for a trial key at that page.

Next, open your ASP.NET MVC C# project. If you don’t have one, you can create it. Alternatively, you can just open our demo project which you can download from the link at the bottom of the page.

 

Creating the action filter class

An action filter is used to perform tasks before or after a controller action executes. In your project, create a sub-folder called Filters if it does not exist. Inside the folder, create a new class called RedirectVisitorsFilter.cs and paste the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace RedirectVisitorsByCountryASPDotNetMVC.Filters
{
    public class RedirectVisitorsFilter : ActionFilterAttribute
    {
        private readonly string[] RedirectCountries = { "US", "GB" };
        private readonly string LicenseKey = "demo"; //replace this with your own IP2Location Web Service API key
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var pat = "\"country_code\":\"([A-Z]{2})\"";
            Regex r = new Regex(pat, RegexOptions.IgnoreCase);
            var data = CallWebService(filterContext.HttpContext.Request.ServerVariables["REMOTE_ADDR"]);
            var countrycode = "";
            Match m = r.Match(data);

            if (m.Success)
            {
                countrycode = m.Groups[1].ToString();
            }

            if (RedirectCountries.Contains(countrycode))
            {
                filterContext.Result = new RedirectResult("https://www.ip2location.com/");
            }
            base.OnActionExecuting(filterContext);
        }

        private string CallWebService(string ip)
        {
            var httpClient = new HttpClient();
            Task<string> data = httpClient.GetStringAsync("https://api.ip2location.com/v2/?key=" + LicenseKey + "&ip=" + ip + "&package=WS1");
            return data.Result;

        }
    }
}

First of all, edit the code to replace the “demo” API key with your actual key. You can also change the RedirectCountries to test other countries. Feel free to edit the URL inside RedirectResult to another website if you so wish. This is the URL that the code will be redirecting to if the visitor’s detected country is in the RedirectCountries list.

NOTE: The IP2Location Web Service is returning the geolocation in the form of JSON hence our use of a regular expression to extract the country code.

 

Levels of redirection

Action filters can be applied on 3 different levels depending on your needs. You could apply the filter on a global scale where every action will be redirected if the country of the IP address is in our specified list. If you prefer a more granular approach, you can also apply the filter only on specific controllers. The last option is to filter only specific controller actions.

 

How to redirect globally

Let’s say you have websites catering to various regions. E.g. Visitors from Europe may need to be redirected to a different website. For this purpose, you will need to redirect on a global level.

Look for the App_Start folder in your project and open the FilterConfig.cs file. Add 1 line containing our action filter class name to the code as below:

using System.Web;
using System.Web.Mvc;

namespace RedirectVisitorsByCountryASPDotNetMVC
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new Filters.RedirectVisitorsFilter()); // redirect globally
            filters.Add(new HandleErrorAttribute());
        }
    }
}

 

How to redirect particular controllers

It is sometimes necessary to redirect only specific controllers for security reasons. To achieve this, you can add an attribute with the name of our action filter class on top of your controller class. Your controller code will look something like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RedirectVisitorsByCountryASPDotNetMVC.Controllers
{
    [Filters.RedirectVisitorsFilter] // redirect by Controller
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

 

How to redirect particular actions

This is the most granular redirection you can perform. You can select which actions in particular you wish to execute the redirection code. The code is similar to the controller redirection case but just the location of the attribute is on top of the specific actions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RedirectVisitorsByCountryASPDotNetMVC.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [Filters.RedirectVisitorsFilter] // redirect by Action
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

 

Download the project

Get the whole project from the link below:

https://www.ip2location.com/downloads/redirect-country-visitors-asp-dotnet-csharp-mvc.zip

Was this article helpful?

Related Articles