質問

Of course that Request.UserHostAddress way is great, however in Application_Start() the Request object isn't exists yet.

I want to first guess the location of user by his/her IP - just one time - as he/she enters the web site, and set the default locale for him/her. Then I'll manipulate it some where else.

I think that there must be an event to be overridden in Global.asax which Request exists in it, However I can't find that event...

Indeed any alternate trick will be appreciated...

Update:

In fact, I'm developing a multilingual web site and I use MaxMind GeoIP to get the country of users by their IP. So, I want to find a way in order that when a user enters the site (only and only the first request) I retrieve his/her country and store it in Session or a global variable.

I know that I can achieve my goal any where else by Request.UserHostAddress and I have not any problem with it - just one line overhead for each request isn't an issue at all for this small app.

However I wonder if it is possible to set that global variable, only and only once...!?!

役に立ちましたか?

解決

Application_Start() is not right event, in which you can do this. It will not run for every request from your user, it does some basic initialization of asp.net application.

Better solution is to user, for example

protected void Application_BeginRequest(){}

which runs on beginning of request from client.

About earliest event, in which both request and session will be available... Seems like it is

void Application_AcquireRequestState(object sender, EventArgs e)
{
    if (System.Web.HttpContext.Current.Session != null)
    {
        if (Session["locale"] != null)
        {                  
             //already set variable. 
        }
        else
        {
            //set some variable
            Session["locale"] = "code";
        }
    }
}

But what exactly do you want to you mean by "setting locale based on IP"? Can you clarify this task? 'Cause in general, for each request execution this "locale" information must be set.

他のヒント

You should do this like this

public void Init(HttpApplication context)
{
    context.BeginRequest += (Application_BeginRequest);
}

private void Application_BeginRequest(object source, EventArgs e)
{
    var context = ((HttpApplication) source).Context;
    var ipAddress = context.Request.UserHostAddress;        
}

It may be solved by using GlobalFilterCollection. You can override the method OnActionExecuting and add the necessary logic. This article: ASP.NET MVC 4 Custom Action Filters may help.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top