HtmlHelper.GenerateRouteLink没有给出预期的结果

时间:2011-09-01 22:03:03

标签: asp.net-mvc hyperlink

我(拼命)试图从我的一个控制器创建一个链接。

看起来应该是这样的:
http://localhost:50074/User/Profile?UserId=17&key=agasgqwefq323432r13dfd

相关(虽然可能是错误的)路线:

routes.MapRoute(
             "UsersRoute", // Route name
            "{controller}/{action}/{userId}/{key}",
             new { controller = "User", action = "Profile",userId=UrlParameter.Optional,key=UrlParameter.Optional });  

链接代码:

HtmlHelper.GenerateRouteLink(requestContext, RouteTable.Routes, "MyLinkText", "UsersRoute", new RouteValueDictionary(new { userId = userId, key = HashPassword(password) } ), null);           

(我通过以下方式发送请求上下文:HttpContext.Request.RequestContext

目前这给了我:

<a href="http://Account/Register/29/E96303852080B94DC230611A3F4806" target="_blank">MyLinkText</a>

(我称之为GenerateRouteLink的上下文是Account / Register,我不知道如何创建一个正确的,如果确实需要的话)

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

在路线定义中,网址格式为:

{controller}/{action}/{userId}/{key}

因此,当您指定{controller}/{action}userid令牌时,我看不出您如何期望表单的网址(key):

/User/Profile?UserId=17&key=agasgqwefq323432r13dfd

为什么不简单地只保留默认的网址定义?

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

然后你可以通过以下方式获得所需形式的网址:

@Html.ActionLink(
    "MyLinkText", 
    "Profile", 
    "User", 
    new { userId = userId, key = HashPassword(password) }, 
    null
)