如何在Asp.Net项目中生成特定语言的Url
本文关键字:语言 Url Asp Net 项目 | 更新日期: 2023-09-27 18:00:32
我使用了西风全球化库http://west-wind.com/westwind.globalization/在我的项目中实现多种语言。一切都很好。只有一个问题是,我在url的末尾获得区域性引用变量http://localhost:18106/LangTest?LocaleId=en.
我希望区域性引用变量介于域名和页面名称之间,如http://localhost:18106/en/LangTest.
我确实想做微软网站http://www.microsoft.com/en-us/default.aspx例如
您需要使用IRouteHandler,并且需要创建自定义路由。
默认情况下,Web窗体使用文件系统请求处理。例如,MyWebsite/contact.aspx请求搜索位于根菜单下的contact.aspx文件。MyWebsite/superoes/superoes.aspx应该在根菜单下的超级英雄文件中查找super英雄.aspx文件。
使用global.asax文件,您可以添加我们自己的处理。您只需要从Application_Start方法中调用一个具有RouteCollection参数的方法。因此,您需要创建一个名为RegisterRoutes的方法,并将其放置在名为MyRouteConfig.cs的新文件中
以下是示例:
using System;
using Microsoft.AspNet.FriendlyUrls;
using System.Web.Routing;
using System.Web;
using System.Web.UI;
using System.Web.Compilation;
public static class MyRouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.EnableFriendlyUrls();
routes.MapPageRoute("superheroes", "superhero/{SuperheroName}", "~/superheroes.aspx");
routes.MapPageRoute("languageSuperheroes", "{language}/superhero/{SuperheroName}", "~/superheroes.aspx");
routes.Add(new System.Web.Routing.Route("{language}/{*page}", new LanguageRouteHandler()));
}
public class LanguageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string page = CheckForNullValue(requestContext.RouteData.Values["page"]);
string virtualPath = "~/" + page;
if (string.IsNullOrEmpty(page))
{
string language= CheckForNullValue(requestContext.RouteData.Values["language"]);
string newPage = "/home";
if (!string.IsNullOrEmpty(language))
newPage = "/" + language + newPage;
HttpContext.Current.Response.Redirect(newPage, false);
HttpContext.Current.Response.StatusCode = 301;
HttpContext.Current.Response.End();
//Otherwise, route to home
//page = "home";
}
if (!virtualPath.Contains(".aspx"))
virtualPath += ".aspx";
try
{
return BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(Page)) as IHttpHandler;
}
catch
{
return null;
}
}
}
}
请看一下这篇文章:http://dotnethints.com/blogs/localization-using-routing-system-on-a-web-forms-project-