3

I have a ASP.Net MVC Web application, In this application i have work to IP detection, IP detection method is taking near about 30 seconds to get the IP, That is fine. But I have only 30 second to run the index page as well as IP detection. Means if i am calling IP detection then there will be no time to load index. I am calling IP detection method from Application_Start(). but when it runs main page have no time to load. I want to call IP detection method after load the application automatically.How it is possible please help.

I have IP detection method as:

public void GetCityByIP()
        {
            abcEntities db = new abcEntities();
            string IPDetect = string.Empty;
            string APIKeyDetect = "Set API key";
            string city = "";
            string cityName = string.Empty;

            if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                IPDetect = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
            {
                IPDetect = "192.206.151.131";
            }
            string urlDetect = string.Format("http://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}&format=json", APIKeyDetect, IPDetect);
            try
            {
                using (WebClient client = new WebClient())
                {
                    string json = client.DownloadString(urlDetect);
                    Location location = new JavaScriptSerializer().Deserialize<Location>(json);
                    List<Location> locations = new List<Location>();
                    locations.Add(location);
                    city = location.CityName;
                }
            }
            catch (WebException e)
            {
                city = "Toronto";
            }
            var getCityID = db.Macities.Where(c => c.CityName.Contains(city)).ToList();

            if ((getCityID != null) && (getCityID.Count > 0))
            {
                cityName = getCityID.FirstOrDefault().CityName;
            }
            else
            {
                getCityID = db.Macities.Where(c => c.CityName.Contains("Toronto")).ToList();
                cityName = getCityID.FirstOrDefault().CityName;
            }
            HttpContext.Current.Response.Cookies["CityName"].Value = cityName;
        }

I want to set cookies and use it as Detected IP city in whole application.I am calling it from Start method as :

 protected void Application_Start()
    {

        GetCityByIP();
    }

IP detection method is also in global file. I have Limited cities in database so that's why i am using database and match city in database cities if it exist then IP method set the city detected in cookies other wise default city will be set in cookies. Thanks in advance.

Amandeep Singh
  • 372
  • 6
  • 20

1 Answers1

0

I'm not sure I really understand in which order you are trying to do things, but you could take a look at Owin and Startup.

http://www.asp.net/aspnet/overview/owin-and-katana/owin-startup-class-detection

Config:

<appSettings>  
  <add key="owin:appStartup" value="StartupDemo.Startup" />
</appSettings>

Code:

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using System.IO;

[assembly: OwinStartup(typeof(StartupDemo.Startup))]

namespace StartupDemo
{
   public class Startup
   {
      public void Configuration(IAppBuilder app)
      {
         app.Use((context, next) =>
         {
            TextWriter output = context.Get<TextWriter>("host.TraceOutput");
            return next().ContinueWith(result =>
            {
               output.WriteLine("Scheme {0} : Method {1} : Path {2} : MS {3}",
               context.Request.Scheme, context.Request.Method, context.Request.Path, getTime());
            });
         });

         app.Run(async context =>
         {
            await context.Response.WriteAsync(getTime() + " My First OWIN App");
         });
      }

      string getTime()
      {
         return DateTime.Now.Millisecond.ToString();
      }
   }
}

Alternatively you can use the Task.Run in order to run it async.

    return TaskEx.Run(() =>
    {

            try
            {
                // Do some time-consuming task.
            }
            catch (Exception ex)
            {
                // Log error.
            }

    });

EDIT AFTER QUESTION UPDATE:

Since it should only run once for each visitor it's more reasonable to put it in Session Start than Application Start. Do not use Owin, as suggested above since it only runs on app start.

Asp.Net MVC OnSessionStart event

void Session_Start(object sender, EventArgs e) {
  // your code here, it will be executed upon session start
}
Community
  • 1
  • 1
smoksnes
  • 10,509
  • 4
  • 49
  • 74