What kind of route would I need to provide vanity urls?

前端 未结 2 2040
执笔经年
执笔经年 2020-12-20 05:59

I\'d like to provide my users a vanity url, something like:

www.foo.com/sergio

What kind of route would I need to create?

Imagine

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-20 06:15

    one solution could be using custom route constraint as,

    public class VanityUrlContraint : IRouteConstraint
    {
        private static readonly string[] Controllers =
            Assembly.GetExecutingAssembly().GetTypes().Where(x => typeof(IController).IsAssignableFrom(x))
                .Select(x => x.Name.ToLower().Replace("controller", "")).ToArray();
    
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
                          RouteDirection routeDirection)
        {
            return !Controllers.Contains(values[parameterName].ToString().ToLower());
        }
    }
    

    and use it as

        routes.MapRoute(
            name: "Profile",
            url: "{username}",
            defaults: new {controller = "Account", action = "Profile"},
            constraints: new { username = new VanityUrlContraint() }
        );
    
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    

    downside of this approach, profile view for usernames same as existing controller name will not work, like if there are usernames like "asset", "location", and "AssetController", "LocationController" exists in project, profile view for "asset", "location" will not work.

    hope this helps.

提交回复
热议问题