Using IP2Location .NET component in ASP.NET MVC with C#

Intro

For this article, we will look into how to integrate the IP2Location .NET component within an 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 a simple form which will submit an IP address to be queried for IP geolocation data.

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 NuGet package
  • IP2Location BIN database file

 

Let’s get started

First of all, you will need to subscribe to the DB24 database at https://www.ip2location.com/database/ip2location and then download the DB24 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/

 

Overview of the codes

As per the model-view-controller (MVC) style of doing things, we will have 3 files. One will be the controller class which is where most of the heavy lifting is done. The second will be our model class which we will use as both the input and output parameters. The last one is the view class where we have a POST form for the user to key in and submit an IP address. The page will also be showing the results of the IP geolocation query.

 

Controller class

Our controller class is called HomeControllers.cs which is the default created by Visual Studio. We have removed the unnecessary codes and added our own Query methods. Please note that there are 2 Query methods. The first one is just to display the form without any input while the second is accepting a POST submission of the IP address. It will then take the IP address and query the IP2Location object to return the geolocation data.

We have opted to declare the IP2Location object as a static variable so that we do not have to initialize it for every query. If it is null then we will initialize the object.

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

namespace IP2LocationASPDotNetMVC.Controllers
{
    public class HomeController : Controller
    {
        private static IP2Location.Component oIP2Location = null;
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            if (oIP2Location == null)
            {
                oIP2Location = new IP2Location.Component
                {
                    IPLicensePath = @"C:\myfolder\license.key",
                    IPDatabasePath = @"C:\myfolder\IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE.BIN"
                };
            }
            base.Initialize(requestContext);
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Query()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Query(Models.IPParam IPParam)
        {
            ViewBag.Message = "IP2Location query page.";

            IPParam.oIPResult = new IP2Location.IPResult();

            IPParam.oIPResult = oIP2Location.IPQuery(IPParam.IP);

            return View(IPParam);
        }

    }
}

 

Model class

Our model class is called IPParam.cs and you can create it under the Models sub-folder of the project. This is the standard location to store model classes. The first variable is called IP and it will store the IP being submitted in the form. The second variable is the IP2Location IPResult object which will store all the geolocation data that is returned.

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

namespace IP2LocationASPDotNetMVC.Models
{
    public class IPParam
    {
        public string IP { get; set; }
        public IP2Location.IPResult oIPResult { get; set; }
    }
}

 

View class

The view class is the front-end page that a user will interact with to submit the IP address and see the results. We’ll call our file Query.cshtml and it is located in the Views\Home\ sub-folder. Convention states that your view class should be under the Views\your controller class name  folder structure.

The first line binds the model class to the view class so that the code will expect the IPParam model class as the parameter. The Html.BeginForm section will generate the HTML form that the user will use to POST the IP address. You can see the results below the form upon submission.

@model IP2LocationASPDotNetMVC.Models.IPParam

@{
    ViewBag.Title = "Query";
}

<h2>Query IP2Location</h2>

@using (Html.BeginForm("Query", "Home", FormMethod.Post))
{
    <table>
        <tr>
            <td style="font-weight: bold; padding-right: 20px;">IP Address</td>
            <td>
                @Html.TextBoxFor(m => m.IP)
                <input type="submit" value="Query IP" />
            </td>
        </tr>
    </table>

}

@if ((Model != null) && (Model.oIPResult != null))
{
    switch (Model.oIPResult.Status)
    {
        case "OK":
            <table>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Country Code</td>
                    <td>
                        @Model.oIPResult.CountryShort
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Country Name</td>
                    <td>
                        @Model.oIPResult.CountryLong
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Region Name</td>
                    <td>
                        @Model.oIPResult.Region
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">City Name</td>
                    <td>
                        @Model.oIPResult.City
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Latitude</td>
                    <td>
                        @Model.oIPResult.Latitude
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Longitude</td>
                    <td>
                        @Model.oIPResult.Longitude
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">ZIP Code</td>
                    <td>
                        @Model.oIPResult.ZipCode
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Time Zone</td>
                    <td>
                        @Model.oIPResult.TimeZone
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">ISP</td>
                    <td>
                        @Model.oIPResult.InternetServiceProvider
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Domain</td>
                    <td>
                        @Model.oIPResult.DomainName
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Net Speed</td>
                    <td>
                        @Model.oIPResult.NetSpeed
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">IDD Code</td>
                    <td>
                        @Model.oIPResult.IDDCode
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Area Code</td>
                    <td>
                        @Model.oIPResult.AreaCode
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Weather Station Code</td>
                    <td>
                        @Model.oIPResult.WeatherStationCode
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Weather Station Name</td>
                    <td>
                        @Model.oIPResult.WeatherStationName
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">MCC</td>
                    <td>
                        @Model.oIPResult.MCC
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">MNC</td>
                    <td>
                        @Model.oIPResult.MNC
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Mobile Brand</td>
                    <td>
                        @Model.oIPResult.MobileBrand
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Elevation</td>
                    <td>
                        @Model.oIPResult.Elevation
                    </td>
                </tr>
                <tr>
                    <td style="font-weight: bold; padding-right: 20px;">Usage Type</td>
                    <td>
                        @Model.oIPResult.UsageType
                    </td>
                </tr>
            </table>
            break;
        case "EMPTY_IP_ADDRESS":
            <div>
                IP Address cannot be blank.
            </div>
            break;
        case "INVALID_IP_ADDRESS":
            <div>
                Invalid IP Address.
            </div>
            break;
        case "MISSING_FILE":
            <div>
                Invalid Database Path.
            </div>
            break;
    }
}

 

Compile and run the codes

After modifying your codes as above, you can compile and run it in Visual Studio. It should launch a browser window for you to test the page. You can now try to submit an IP via the form and see the geolocation results. If you key in an invalid IP address, expect to see an error message. Same goes if you have put the wrong path for the BIN file in the codes.

You can download the whole project from the below link:

https://www.ip2location.com/downloads/ip2ocation-asp-dotnet-csharp-mvc.zip

 

Was this article helpful?

Related Articles