【发布时间】:2016-08-24 07:40:01
【问题描述】:
我正在尝试根据用户的 IP 地址位置将用户重定向到子域。我有一个页面加载观察器,它在每个请求上运行一个函数,它获取用户位置,当我尝试重定向到另一个域时,它给了我“重定向太多”错误,我想不出解决这个问题的方法.
目前我的代码如下所示
string CountryName = "";
var Country = HttpContext.Current.Response.Cookies["Country"];
Country.Expires = DateTime.Now.AddDays(365);
var ip = HttpContext.Current.Request.UserHostAddress;
if (!string.IsNullOrEmpty(ip) && ip != null && ip != "127.0.0.1")
{
using (var client = new WebServiceClient(xxxxx, "xxxxxxxx"))
{
var IpCountry = client.Country(ip);
CountryName = IpCountry.Country.Name;
}
switch (CountryName)
{
case "Denmark":
if (Country.Value != CountryName)
{
Country.Value = CountryName;
HttpContext.Current.Response.Redirect("/");
}
break;
case "United Kingdom":
if (Country.Value != CountryName)
{
Country.Value = CountryName;
HttpContext.Current.Response.Redirect("/en");
}
break;
case "Germany":
if (Country.Value != CountryName)
{
Country.Value = CountryName;
HttpContext.Current.Response.Redirect("/de");
}
break;
case "Sweden":
if (Country.Value != CountryName)
{
Country.Value = CountryName;
HttpContext.Current.Response.Redirect("/se");
}
break;
case "Norway":
if (Country.Value != CountryName)
{
Country.Value = CountryName;
HttpContext.Current.Response.Redirect("/no");
}
break;
default:
if (Country.Value != CountryName)
{
Country.Value = CountryName;
//HttpContext.Current.Response.Redirect("http://www.google.com");
}
break;
}
}
else if (loadedArgs.pageview.Area.ID != 2)
{
HttpContext.Current.Response.Redirect("/choose-country");
}
此外,我还想知道以更好的方式处理这种情况的其他可能方法,因此一旦设置了 cookie,此代码就不会在每次页面加载时运行。非常感谢。
【问题讨论】:
-
您的意思是,当您取消注释重定向到谷歌时,您会收到许多重定向错误?
-
@VolodymyrBilyachat 不,当我注释掉所有重定向时它工作正常,否则它会给我错误重定向太多。这虽然有意义,因为此代码在页面加载时运行,并且在重定向后再次运行代码并进入无限循环。所以我想弄清楚如何预防?
-
你实际上在哪里设置带有国家名称的cookie?
-
@Evk cookie 设置在 Country 变量中,并且在获取 CountryName 后,我正在存储类似 Country.Value = CountryName; 的值
-
使用自定义 http 处理程序为您处理此问题可能是更清洁的解决方案。
标签: c# .net redirect http-redirect response.redirect