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

2019-03-06 11:30发布

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.

2条回答
劫难
2楼-- · 2019-03-06 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.....

查看更多
ら.Afraid
3楼-- · 2019-03-06 12:09

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.

查看更多
登录 后发表回答