C# 使用Sitecore CMS管道处理器,如何根据用户的IP地址重定向用户?

C# 使用Sitecore CMS管道处理器,如何根据用户的IP地址重定向用户?,c#,geolocation,ip,sitecore,pipeline,C#,Geolocation,Ip,Sitecore,Pipeline,我正试图使用httpRequestBegin管道处理器来实现这一点,但我似乎无法从给定的HttpRequestArgs参数访问用户的IP地址 当我实现一个具有此方法的类时 public void Process(HttpRequestArgs args) { string ipAddress = args.Context.Request.UserHostAddress; // Not working string state = GetState(ipAddress); // a

我正试图使用httpRequestBegin管道处理器来实现这一点,但我似乎无法从给定的HttpRequestArgs参数访问用户的IP地址

当我实现一个具有此方法的类时

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
}
我想这可能包含用户的IP地址

args.Context.Request.UserHostAddress
但它反而会导致此错误(堆栈跟踪说它源自Process方法):

有什么想法吗?谢谢

编辑,这在Sitecore 6.1和web.config中

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

您定义管道的地方很好<代码>args.Context.Request应在请求处理的此步骤中可用。最可能的原因是在上下文不可用的特定情况下调用此处理器。应对这些情况进行以下简单检查:

if (args.Context != null)
{
    //....
}
我能想到的唯一其他解释是
GetState()
RedirectUserByState()
正在调用
HttpContext.Current
,这在此时不可用(因此Sitecore将上下文作为参数传递)

此外,负载平衡器不会解释异常,但如果IP始终相同,则您可能会更幸运地检查以下服务器变量:

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

这应该很好(至少对我来说是这样)。您能告诉我们您在配置中定义管道的位置吗?另外,您是否支持负载平衡器?另外,您可能希望确保
GetState()
RedirectUserByState()
不使用HttpContext.Current.Request/Response。如果他们这样做了,您将希望将args.Context传递给这些方法。感谢您的回复。这两种方法都不使用HttpContext.current谢谢您的回复!我确信这将停止错误,但如果上下文总是空的,我不确定是否会重定向单个用户。我将记录每一次出现的空上下文和每一次成功的IP地址重定向并报告回来。值得一提的是,在没有上下文的情况下调用这些管道是很正常的。如果您反映了实际的Sitecore管道,则大多数管道都有相应的检查(尽管有些管道根据需要而有所不同)。例如,检查
Sitecore.Context.Item!=null
,这将是一个很好的方法,可以确保它是实际用户访问某个项目,而不是某个内部客户端请求或资源。我使用的是流程函数下方的
Sitecore.Context.request
Sitecore.Context.Response
。这是导致错误的原因。谢谢你的帮助!
if (args.Context != null)
{
    //....
}
args.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
args.Request.ServerVariables["REMOTE_ADDR"]