我需要什么样的路线来提供虚荣网址? [英] What kind of route would I need to provide vanity urls?

查看:12
本文介绍了我需要什么样的路线来提供虚荣网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的用户提供一个个性化网址,例如:

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?

假设我有以下控制器和操作,如何将虚 URL 映射到该控制器?

Imagine I have the following controller and action, how can I map a vanity URL to that controller?

public ActionResult Profile(string username)
{
    var model = LoadProfile(username);
    return View(model);
}

<小时>

这是我尝试过的以及发生了什么:


Here is what I've tried and what happens:

每个 url 都被这个路由捕获,这意味着我输入的每个 URL 都将我引导到 Account 控制器,而不仅仅是 foo.com/[USERNAME].不好.

Every url is caught in this route, meaning every URL I type directs me towards the Account controller, instead of only foo.com/[USERNAME]. No good.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
}

<小时>

选项 B:

默认路由运行良好,但在尝试访问配置文件时 foo.com/[USERNAME] 我收到 HTTP 404 错误.


Option B:

Default routes work well, but when trying to visit a profile foo.com/[USERNAME] I get an HTTP 404 error.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

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

推荐答案

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

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

这种方法的缺点是,与现有控制器名称相同的用户名的配置文件视图将不起作用,例如如果有像asset"、location"和AssetController"这样的用户名,则项目中存在LocationController",配置文件视图为资产"、位置"将不起作用.

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.

希望这会有所帮助.

这篇关于我需要什么样的路线来提供虚荣网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆