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

妖精的绣舞 提交于 2019-11-29 08:57:23

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.

Have you tried:

routes.MapRoute(
"YourRouteName",
"{username}",
new {controller="YourController", action="Profile", username=UrlParameter.Optional}
);

This should trap www.foo.com/{username}. Remember that routes are checked in the order you add them, so you can add

routes.MapRoute(
"default",
"{controller}/{action}/{input}",
new {controller="controller", action="action", input=UrlParameter.Optional}
);

first to maintain the "default" behavior.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!