简体   繁体   中英

Using a Sitecore CMS pipeline processor, how do I redirect a user based on their IP address?

I am trying to do this with an httpRequestBegin pipeline processor, but I don't seem to be able to access the user's IP address from the given HttpRequestArgs parameter.

When I implement a class that has this method

public void Process(HttpRequestArgs args) {
    string ipAddress = args.Context.Request.UserHostAddress; // Not working
    string state = GetState(ipAddress); // already implemented elsewhere
    RedirectUserByState(state);  // already implemented elsewhere
}

I thought that this might hold the user's IP address

args.Context.Request.UserHostAddress

but it causes this error instead (stack trace says it originates from the Process method):

System.Web.HttpException: Request is not available in this context

Any ideas? Thanks!

Edit, this is in Sitecore 6.1 and in the web.config at

<pipelines>
<!--...-->
    <httpRequestBegin>
        <!--...-->
        <processor type="Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel"/>
        <processor type="MySolution.Redirector, MySolution"/>
        <processor type="Sitecore.Pipelines.HttpRequest.LayoutResolver, Sitecore.Kernel"/>
        <!--...-->
    </httpRequestBegin>
    <!--...-->
</pipelines>

This server might be behind a load balancer.

Edit 2: It looks like I was trying to access both of these inside the Process() function and that is what was causing the error:

Sitecore.Context.Request
Sitecore.Context.Response

Where you defined your pipeline is fine. args.Context.Request should be available at this step in the request processing. The most likely cause is that this processor is being evoked under certain circumstances where the Context is not available. A simple check for the following should handle those cases:

if (args.Context != null)
{
    //....
}

The only other explanation I can think of is that GetState() or RedirectUserByState() are calling HttpContext.Current which is not available at this point (hence why Sitecore passes the context as an argument).

Also, a load-balancer would not explain the exceptions, but you may have better luck checking for the following server variables if the IP ends up always be the same:

args.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
args.Request.ServerVariables["REMOTE_ADDR"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM