当前位置:  开发笔记 > 编程语言 > 正文

在ASP.net中处理多语言网站中的URL的最佳方法

如何解决《在ASP.net中处理多语言网站中的URL的最佳方法》经验,为你挑选了1个好方法。

我需要做一个多语言的网站,网址就像

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处理,而不是关于资源等.



1> Eduardo Molt..:

我决定使用新的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

推荐阅读
吻过彩虹的脸_378
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有