asp.net mvc. Routing and Url building

前端 未结 2 1119
悲哀的现实
悲哀的现实 2021-02-11 07:20

Does any body knows how to hide some parameters in url?

For example you have a url parameter \"culture\". It can be \"en, fr, it\". By default your site renders in \"en\

2条回答
  •  天命终不由人
    2021-02-11 07:53

    The following RouteConstraint might help,

    public class CultureConstraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
                          RouteDirection routeDirection)
        {
            if (routeDirection == RouteDirection.UrlGeneration)
            {
                return values[parameterName] != null &&
                       (route.Defaults[parameterName] == null ||
                        values[parameterName].ToString().ToLower() != route.Defaults[parameterName].ToString().ToLower());
            }
            return true;
        }
    }
    

    Use it as,

    routes.MapRoute(
        name: "Culture",
        url: "{culture}/{controller}/{action}/{id}",
        defaults: new {culture = "en", controller = "Home", action = "Index", id = UrlParameter.Optional},
        constraints: new {culture = new CultureConstraint()}
    );
    
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional}
    );
    

    Here the constraint only works on outbound url and discard the route for candidacy when 'culture' in route information equals to default.

    I used the simplest implementation because you have not posted your route code, but the idea should work.

    hope this helps.

提交回复
热议问题