Add language name in URL by using Routing in Asp.net

前端 未结 2 610
抹茶落季
抹茶落季 2021-01-26 11:14

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

相关标签:
2条回答
  • 2021-01-26 12:00

    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.

    0 讨论(0)
  • 2021-01-26 12:01

    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.....

    0 讨论(0)
提交回复
热议问题