Blocking country visitors in ASP.NET MVC with C#

Intro

For this article, we will look into how to use the IP2Location .NET Component to block website visitors in ASP.NET MVC 5 project. We will assume that you already know the basics of ASP.NET MVC so we will just show the relevant codes using C#. Our example will be blocking visitors from the United States and Sweden.

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

https://learn.microsoft.com/en-us/shows/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 NuGet package
  • IP2Location BIN database file

Let’s get started

First of all, you will need to subscribe to the DB26 database at https://www.ip2location.com/database/ip2location and then download the DB26 BIN database file. Inside the downloaded zipped file, you will find a BIN file. Extract that file and save it somewhere, e.g. C:\myfolder\ for use later.

Next, open your ASP.NET MVC C# project. If you don’t have one, you can create it. Then inside the Visual Studio, install the following IP2Location NuGet package.

https://www.nuget.org/packages/IP2Location.IPGeolocation/

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 BlockVisitorsFilter.cs and paste the code below:

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

namespace BlockVisitorsByCountryASPDotNetMVC.Filters
{
    public class BlockVisitorsFilter : ActionFilterAttribute
    {
        private static IP2Location.Component oIP2Location = null;
        private readonly string[] BlockedCountries = { "US", "SE" };

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (oIP2Location == null)
            {
                oIP2Location = new IP2Location.Component
                {
                    IPDatabasePath = @"C:\myfolder\IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-ADDRESSTYPE-CATEGORY-DISTRICT-ASN.BIN"
                };
            }

            IP2Location.IPResult oIPResult = new IP2Location.IPResult();
            oIPResult = oIP2Location.IPQuery(filterContext.HttpContext.Request.ServerVariables["REMOTE_ADDR"]);

            if (oIPResult.Status == "OK")
            {
                if (BlockedCountries.Contains(oIPResult.CountryShort))
                {
                    filterContext.Result = new HttpStatusCodeResult(403);
                }
            }

            base.OnActionExecuting(filterContext);
        }
    }
}

The above code is checking whether the web visitor’s IP is in the blocked countries list. In our example, we are blocking visitors from the United States (US) and Sweden (SE). You will need to modify this list to block your own list of countries.

We are overriding the original OnActionExecuting function which is called before the action method is invoked. If we find that the country of the visitor’s IP address is in the list, we will show a HTTP 403 Forbidden message on their browser.

Although the above code is just checking the country and blocking accordingly, you could check other parameters like regions and cities too. You just need to make sure you get the right BIN database file. Refer to https://www.ip2location.com/database/ip2location for the types of data contained within each of the BIN files.

Levels of blocking

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 blocked if the country of the IP address is blacklisted. 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 block globally

Due to regulations or security concerns, you might want to prevent users of specific nations from accessing your entire website. For this, you will need to block 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 BlockVisitorsByCountryASPDotNetMVC
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new Filters.BlockVisitorsFilter()); // blocking globally
            filters.Add(new HandleErrorAttribute());
        }
    }
}

How to block particular controllers

When you only want to target your blocking on specific controllers, you can do so by adding 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 BlockVisitorsByCountryASPDotNetMVC.Controllers
{
    [Filters.BlockVisitorsFilter] // blocking 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 block particular actions

This is the most granular blocking you can perform. You can select which actions in particular you wish to perform the country blocking. The code is similar to the controller blocking 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 BlockVisitorsByCountryASPDotNetMVC.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [Filters.BlockVisitorsFilter] // blocking 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/block-country-visitors-asp-dotnet-csharp-mvc.zip

Was this article helpful?

Related Articles