我需要做一个多语言的网站,网址就像
www.domain.com/en/home.aspx for english www.domain.com/es/home.aspx for spanish
在过去,我会在IIS中设置两个虚拟目录,然后在global.aspx中检测URL并根据URL更改语言
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) Dim lang As String If HttpContext.Current.Request.Path.Contains("/en/") Then lang = "en" Else lang = "es" End If Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang) End Sub
解决方案更像是黑客攻击.我正在考虑将路由用于新网站.
你知道更好或更优雅的方式吗?
编辑:问题是关于URL处理,而不是关于资源等.
我决定使用新的ASP.net路由.
为什么不urlRewriting?因为我不想更改路由为您提供的干净URL.
这是代码:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ' Code that runs on application startup RegisterRoutes(RouteTable.Routes) End Sub Public Sub RegisterRoutes(ByVal routes As RouteCollection) Dim reportRoute As Route Dim DefaultLang As String = "es" reportRoute = New Route("{lang}/{page}", New LangRouteHandler) '* if you want, you can contrain the values 'reportRoute.Constraints = New RouteValueDictionary(New With {.lang = "[a-z]{2}"}) reportRoute.Defaults = New RouteValueDictionary(New With {.lang = DefaultLang, .page = "home"}) routes.Add(reportRoute) End Sub
然后LangRouteHandler.vb类:
Public Class LangRouteHandler Implements IRouteHandler Public Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler _ Implements System.Web.Routing.IRouteHandler.GetHttpHandler 'Fill the context with the route data, just in case some page needs it For Each value In requestContext.RouteData.Values HttpContext.Current.Items(value.Key) = value.Value Next Dim VirtualPath As String VirtualPath = "~/" + requestContext.RouteData.Values("page") + ".aspx" Dim redirectPage As IHttpHandler redirectPage = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, GetType(Page)) Return redirectPage End Function End Class
最后,我使用root中的default.aspx重定向到浏览器列表中使用的默认lang.
也许这可以通过route.Defaults来完成,但是在Visual Studio中不起作用(也许它可以在服务器中运行)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim DefaultLang As String = "es" Dim SupportedLangs As String() = {"en", "es"} Dim BrowserLang As String = Mid(Request.UserLanguages(0).ToString(), 1, 2).ToLower If SupportedLangs.Contains(BrowserLang) Then DefaultLang = BrowserLang Response.Redirect(DefaultLang + "/") End Sub
一些消息来源:
*Mike Ormond的博客
*Chris Cavanagh的Blog
*MSDN