How we can add language name in URL by using Routing?
my site runs on http://localhost:41213/default.aspx URL successfully but this site in multilingual and my client wants run this site according to language like he wants http://localhost:41213/en/default.aspx instead of http://localhost:41213/default.aspx URL.
So my problem is that how to add en,es,hi,etc in URL and how to read this? default.aspx page is on root directory and it is home page.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Use this code in global.asax
public static void RegisterRoutes(System.Web.Routing.RouteCollection routes)
{
routes.Add(new System.Web.Routing.Route("{language}/{*page}", new CustomRouteHandler()));
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(System.Web.Routing.RouteTable.Routes);
}
void Application_BeginRequest(object sender, EventArgs e)
{
string URL = HttpContext.Current.Request.Url.PathAndQuery;
string language = TemplateControlExtension.Language;
if (URL.ToLower() == "/default.aspx")
{
HttpContext.Current.Response.Redirect("/" + language + URL);
}
}
make a router handler class like this…
public class CustomRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string language = TemplateControlExtension.GetString(null, requestContext.RouteData.Values["language"]).ToLower();
string page = TemplateControlExtension.GetString(null, requestContext.RouteData.Values["page"]).ToLower();
if (string.IsNullOrEmpty(page))
{
HttpContext.Current.Response.Redirect("/" + language + "/default.aspx");
}
string VirtualPath = "~/" + page;
if (language != null)
{
if (!VIPCultureInfo.CheckExistCulture(language))
{
HttpContext.Current.Response.Redirect("/" + SiteSettingManager.DefaultCultureLaunguage + "/default.aspx");
}
TemplateControlExtension.Language = language;
}
try
{
if (VirtualPath.Contains(".ashx"))
{
return (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(IHttpHandler));
}
return BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;
}
catch
{
return null;
}
}
}
By using this i hope your requirement has fulfill…..
Method 2
Probably the best way to do this is to have an initial page where he chooses the language he wants. Then the site loads a cookie to his browser indicating his language preference. In subsequent visits, your site reads the cookie and automatically takes him to his language preference.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0