ASP.NET MVC, localized routes and the default language for the user

前端 未结 4 618
臣服心动
臣服心动 2020-12-08 05:28

I am using ASP.NET MVC localized routes. So when a user goes to the English site it is example.com/en/Controller/Action and the Swedish site is example.co

4条回答
  •  余生分开走
    2020-12-08 06:11

    This is how I would do it.

    ~~ Disclaimer : psuedo code ~~

    global.asax

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{*favicon}",
            new { favicon = @"(.*/)?favicon.ico(/.*)?" });
    
        routes.MapRoute(
            "Question-Answer", // Route name
            "{languageCode}/{controller}/{action}", // URL with parameters
            new {controller = "home", action = "index"} // Parameter defaults
            );
    
    }
    

    Take note: the controller and/or action do NOT need to be first and second. in fact, they do not need to exist at all, in the url with parameters section.

    Then ...

    HomeController.cs

    public ActionResult Index(string languageCode)
    {
       if (string.IsNullOrEmpty(languageCode) ||
          languageCode != a valid language code)
       {
           // No code was provided OR we didn't receive a valid code 
           // which you can't handle... so send them to a 404 page.
           // return ResourceNotFound View ...
       }
    
       // .. do whatever in here ..
    }
    

    Bonus suggestion

    You can also add a Route Constraint to your route, so it only accepts certain strings for the languageCode parameter. So stealing this dude's code ....

    (more pseduo code)...

    public class FromValuesListConstraint : IRouteConstraint
    {
        public FromValuesListConstraint(params string[] values)
        {
            this._values = values;
        }
    
        private string[] _values;
    
        public bool Match(HttpContextBase httpContext,
            Route route,
            string parameterName,
            RouteValueDictionary values,
            RouteDirection routeDirection)
        {
            // Get the value called "parameterName" from the 
            // RouteValueDictionary called "value"
            string value = values[parameterName].ToString();
    
            // Return true is the list of allowed values contains 
            // this value.
            return _values.Contains(value);
        }
    }
    

    means you could do this ......

    routes.MapRoute(
        "Question-Answer", // Route name
        "{languageCode}/{controller}/{action}", // URL with parameters
        new {controller = "home", action = "index"} // Parameter defaults
        new { languageCode = new FromValuesListConstraint("en", "sv", .. etc) }
        );
    

    and there you have it :)

    I do something like this for versioning my MVC Api.

    GL :) Hope this helps.

提交回复
热议问题