【问题标题】:Using a Sitecore CMS pipeline processor, how do I redirect a user based on their IP address?使用 Sitecore CMS 管道处理器,我如何根据用户的 IP 地址重定向用户?
【发布时间】:2012-08-20 07:57:09
【问题描述】:

我正在尝试使用 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 方法):

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

有什么想法吗?谢谢!

编辑,这是在 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>

此服务器可能位于负载平衡器后面。

编辑 2: 看起来我 正在 尝试在 Process() 函数中访问这两个,这就是导致错误的原因:

Sitecore.Context.Request
Sitecore.Context.Response

【问题讨论】:

  • 这应该可以正常工作(至少它对我有用)。你能告诉我们你在配置中定义管道的位置吗?另外,您是否支持负载均衡器?
  • 另外,您可能希望确保 GetState()RedirectUserByState() 不使用 HttpContext.Current.Request/Response。如果他们这样做,您需要将 args.Context 传递给这些方法。
  • 感谢您的回复。这些方法都没有使用 HttpContext.Current

标签: c# geolocation ip sitecore pipeline


【解决方案1】:

您定义管道的位置很好。 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"]

【讨论】:

  • 感谢您的回复!我确信这会阻止错误,但如果上下文始终为空,我不确定我是否会重定向单个用户。我将记录每一次出现的空上下文和每一次成功的 IP 地址重定向并报告。
  • 不管怎样,这些管道在没有上下文的情况下被调用是很正常的。如果您反映实际的 Sitecore 管道,它们中的大多数都进行了检查(尽管有些根据需要而有所不同)。例如,一些检查Sitecore.Context.Item != null,这将是确保它是访问项目的实际用户而不是某些内部客户端请求或资源的好方法。
  • 我在 Process 函数中使用了Sitecore.Context.RequestSitecore.Context.Response。那是导致错误的原因。感谢您的帮助!
猜你喜欢
  • 2020-03-28
  • 2012-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
相关资源
最近更新 更多