asp.net mvc multilanguage urls/routing

前端 未结 3 1162
太阳男子
太阳男子 2020-12-04 17:21

This is a two part question regarding asp.net mvc multilanguage urls/routing and SEO best practices/benefits…

Question Part 1)

I’m being ask

3条回答
  •  旧时难觅i
    2020-12-04 17:39

    To achieve what you want you basically need to implement three things:

    A multi-language aware route to handle incoming URLs:

    routes.MapRoute(
        name: "DefaultLocalized",
        url: "{lang}/{controller}/{action}/{id}",
        constraints: new { lang = @"(\w{2})|(\w{2}-\w{2})" },   // en or en-US
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    

    A LocalizationAttribute to handle these kinds of multi-language requests:

    public class LocalizationAttribute : ActionFilterAttribute
    {
        private string _DefaultLanguage = "en";
    
        public LocalizationAttribute(string defaultLanguage)
        {
            _DefaultLanguage = defaultLanguage;
        }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string lang = (string)filterContext.RouteData.Values["lang"] ?? _DefaultLanguage;
            if (lang != _DefaultLanguage)
            {
                try
                {
                    Thread.CurrentThread.CurrentCulture =
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
                }
                catch (Exception e)
                {
                    throw new NotSupportedException(String.Format("ERROR: Invalid language code '{0}'.", lang));
                }
            }
        }
    }
    

    An helper method to generate these URLs within your application: this can be done in multiple ways, depending on your application logic. For example, if you need to do it within your Razor Views, the best thing you can do is to write a couple extension methods to make your Html.ActionLink and Url.Action accept a CultureInfo object as a parameter (and/or use CultureInfo.CurrentCulture as the default one), such as the following:

    • Code sample for multi-language Html.ActionLink extension
    • Code sample for multi-language Url.Action extension

    (both are written in C#)

    You can also avoid the extension method pattern and write them as MultiLanguageActionLink / MultiLanguageAction instead.

    For additional info and further samples on this topic you can also read this post on my blog.

提交回复
热议问题