我有两个要求
第一条是:我的要求是在所有网址中添加国家代码。在我的url看起来像
www.mysite.net/catalog.aspx . www.mysite.net/product.aspx www.mysite.net/cart.aspx
但是现在我必须在全局的地方写一些代码,它将在所有url中注入2 char国家代码,只需读取cookie值。所以我的新网址看起来就像
Www.mysite.net/uk/Cato.aspx www.mysite.net/uk/product.aspx www.mysite.net/uk/cart.aspx
所以,告诉我,我需要添加什么代码,在全球地区的网站,注入国家代码的网址。
第二,当国家代码被注入到浏览器地址栏的url中时,我所有页面中的所有链接都应该有相同的国家代码。
如果可能的话,可以用代码示例和提示来讨论这一点。一个人告诉我下载并安装IIS重写模块,但我不知道IIS重写模块如何注入从country cookie读取的国家代码。我想我需要为此添加一些代码。
我能用asp.net mvc中的url路由来解决这个问题吗?寻求帮助。
谢谢
发布于 2016-07-18 11:17:38
这样我就完成了这份工作。所以我喜欢分享这可能会对别人有所帮助。
我的Application_BeginRequest看起来就像
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string CountryCodeInUrl = "", redirectUrl="";
var countryCode = CookieSettings.ReadCookie();
if (countryCode=="")
{
countryCode = "gb";
}
if (HttpContext.Current.Request.RawUrl.Length >= 2)
{
CountryCodeInUrl = HttpContext.Current.Request.RawUrl.Substring(1, 2);
}
if (countryCode != CountryCodeInUrl)
{
if (HttpContext.Current.Request.RawUrl.Length >= 2)
{
if (HttpContext.Current.Request.RawUrl.Substring(1, 2) != "")
{
countryCode = HttpContext.Current.Request.RawUrl.Substring(1, 2);
}
}
if(!System.Web.HttpContext.Current.Request.RawUrl.Contains(countryCode))
{
redirectUrl = string.Format("/{0}{1}", countryCode, System.Web.HttpContext.Current.Request.RawUrl);
}
else
{
redirectUrl = System.Web.HttpContext.Current.Request.RawUrl;
}
CookieSettings.SaveCookie(countryCode);
System.Web.HttpContext.Current.Response.RedirectPermanent(redirectUrl);
}
}CookieSettings类
public class CookieSettings
{
public static void SaveCookie(string data)
{
var _CookieValue= new HttpCookie("CountryCookie");
_CookieValue.Value = data;
_CookieValue.Expires = DateTime.Now.AddDays(300);
HttpContext.Current.Response.Cookies.Add(_CookieValue);
}
public static string ReadCookie()
{
var _CookieValue = "";
if (HttpContext.Current.Request.Cookies["CountryCookie"] != null)
_CookieValue= HttpContext.Current.Request.Cookies["CountryCookie"].Value;
return _CookieValue;
}
}例程配置如下所示
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultCountry",
url: "{countrycode}/{controller}/{action}/{id}",
defaults: new {countrycode="gb", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}家庭控制器索引操作看起来像
public ActionResult Index(string countrycode)
{
return View();
}这个问题已经结束了。
https://stackoverflow.com/questions/38414957
复制相似问题