i am using webform and my .net framework version is 4.5. i need to inject country code in url. i could inject it from global.asax file.
here is the code
- protected void Application_BeginRequest(Object sender, EventArgs e)
- {
- string rawUrl = HttpContext.Current.Request.RawUrl;
- //check for 2 characters wrapped in forward slashes eg. /en/
- string countryCode = Utility.GetCountryCodeFromUrl(rawUrl);
- SiteCulture Culture = SiteGlobalization.DefaultCulture;
- if (string.IsNullOrEmpty(countryCode))
- {
- //check cookie
- if (!string.IsNullOrEmpty(Utility.GetCookieValue()))
- {
- string threeDigitIsoRegionCodeCookie = Utility.GetCookieValue();
- Culture = SiteGlobalization.BBACultures.Values.FirstOrDefault(x => x.ThreeDigitISORegionCode.Equals(threeDigitIsoRegionCodeCookie, StringComparison.InvariantCultureIgnoreCase));
- if (Culture != null && !string.IsNullOrEmpty(Culture.TwoDigitISORegionCode))
- {
- countryCode = Culture.TwoDigitISORegionCode;
- }
- }
- //check the referer.
- if (string.IsNullOrEmpty(countryCode) && HttpContext.Current.Request.UrlReferrer != null && !string.IsNullOrEmpty(HttpContext.Current.Request.UrlReferrer.AbsolutePath))
- {
- countryCode = Utility.GetCountryCodeFromUrl(HttpContext.Current.Request.UrlReferrer.AbsolutePath);
- }
- //finally browser
- countryCode = string.IsNullOrEmpty(countryCode) ? Utility.Get2DigitCountryCodeFromBrowser().ToLower() : countryCode;
- string redirectUrl = string.Format("/{0}{1}", countryCode, rawUrl);
- HttpContext.Current.Response.RedirectPermanent(redirectUrl.ToLower());
- }
- /* is the country code valid ? */
- Culture = SiteGlobalization.BBACultures.Values.FirstOrDefault(x => x.TwoDigitISORegionCode.Equals(countryCode, StringComparison.InvariantCultureIgnoreCase));
- if (Culture == null || string.IsNullOrEmpty(Culture.ThreeDigitISORegionCode))
- {
- HttpContext.Current.Response.RedirectPermanent(string.Format("/{0}/index.aspx", SiteGlobalization.DefaultCulture.TwoDigitISORegionCode.ToLower()));
- }
- if (HttpContext.Current.Request.FilePath.EndsWith("/" + countryCode))
- {
- HttpContext.Current.Response.RedirectPermanent(string.Format("/{0}/index.aspx", countryCode.ToLower()));
- }
- /* set the default cutlure */
- Utility.SetCountry(Culture);
- }
the above code is working and injecting country code as per cookie value. so when i run my project from VS2013 IDE then url look like http://localhost:53741/gb/ or http://localhost:53741/gb/default
but getting error when browsing from IDE. because there is no folder called gb in my project.
so i add rewrite rule and that is as follows
- <rewrite>
- <rules>
- <rule name="Rewrite language code">
- <match url="^([a-z]+)/([0-9a-z]+).aspx" />
- <action type="Rewrite" url="/{R:2}.aspx?lang={R:1}" />
- rule>
- rules>
- rewrite>
- xml version="1.0" encoding="utf-8"?>
- answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.