且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我需要什么样的路线来提供虚名网址?

更新时间:2023-11-27 22:18:04

一种解决方案可能是使用自定义路由约束,

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());
    }
}

并将其用作

    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.

希望这会有所帮助.