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

喜你入骨 提交于 2019-12-12 04:08:40

问题


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

回答1:


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"]


来源:https://stackoverflow.com/questions/12114710/using-a-sitecore-cms-pipeline-processor-how-do-i-redirect-a-user-based-on-their

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!