我想将用户名作为url参数

时间:2012-03-18 21:39:33

标签: asp.net asp.net-mvc razor

我是ASP.NET MVC 3的新手,我希望使用ASP.NET MVC将username / id作为URL参数。

例如,我希望:

http://mylink.com/username 

http://mylink.com/id

重定向到我的HomeController操作Profile

这可能吗?

我尝试使用

创建新路线
routes.MapRoute(
            "Profile", // Route name
            "{controller}/{id}", // URL with parameters
            new { controller = "Home", action = "Profile", id = UrlParameter.Optional } // Parameter defaults 
        );

但它不起作用。

由于

1 个答案:

答案 0 :(得分:3)

您应该能够完成您所追求的网址格式。这是一个应该有效的例子:

路线代码:

// be sure to register your custom route before the default routes
routes.MapRoute(null, // route name is not necessary
    "{username}",
    new { controller = "Home", action = "Profile", }
);

routes.MapRoute(null,
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

控制器代码:

public class HomeController : Controller
{
    public ActionResult Profile(string username)
    {
        // http://mylink.com/myusername should hit this method
    }
}

对评论1的回复

我不想在不了解您的项目或您正在设计的URL架构的情况下回答已加载的问题。但是我马上发现它有问题。你说你想要至少有2个URL:

根据定义,这意味着您不能拥有任何用户名为“关于”的用户。否则,系统永远不会知道要传递的内容 - 关于页面,或用户名“about”的个人资料页面。在MVC中,URL是不区分大小写的。

如果您要创建包含更多页面的更大应用程序,我建议您为“个人档案”操作设置范围。也许更像是这样的事情:

话虽如此,您仍然可以完成所需的网址格式。但是您必须添加几个验证以确保没有用户具有与您的其他路由匹配的用户名,并且您将必须编写更多自定义路由。所以你真的只是为自己做更多的工作。您必须在路线中执行以下操作:

// more specific routes must be added first

routes.MapRoute(null,
    "About",
    new { controller = "Home", action = "About", }
);

routes.MapRoute(null,
    "{username}",
    new { controller = "Home", action = "Profile", }
);

routes.MapRoute(null,
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

以上路由会将/ About对About操作的请求以及对Profile操作的所有其他/ somestring请求进行匹配。