返回RedirectToAction(...)更漂亮的网址

时间:2016-01-23 11:28:29

标签: asp.net-mvc-4 url-redirection redirecttoaction

调用RouteConfig.cs方法时,有没有办法维护RedirectToAction映射中定义的链接格式?

ex [仅供测试]:

我有这条路线:

routes.MapRoute(
 "Token Verification",
 "Registration/TokenVerification/{ConfernceId}/{TokenType}/{TokenId}/{Email}",
new{
  controller="Registration",
  action="TokenVerification",
  ConfernceId= 0,
  TokenType='\0',
  TokenId="",
  Email=""
 }
);

如果路由正确,我可以调用此链接和我的操作:

  

http://localhost:49619/Registration/TokenVerification/2/R/asdasdasd/someone@somewhere.com

但如果我致电RedirectToAction,则会生成以下url

  

http://localhost:49619/Registration/TokenVerification?ConfernceId=2&TokenType=R&Email=someone%40somewhere.com

它也有效,但它根本不漂亮!

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

使用RedirectToRoute(来自MSDN)生成指定路径格式的网址。

 return RedirectToRoute("Token Verification", new
        {
            ConfernceId = 0,
            TokenType = "0",
            TokenId = "0",
            Email = "0"
        });

如果您想生成链接,请查看以下内容。 使用Url.RouteUrl(检查MSDN资源)。比如说 -

@Url.RouteUrl("DefaultApi", new { httproute=true, controller="Albums", id=3})

将生成/api/Albums/3

在你的情况下,它应该是 -

@Url.RouteUrl("Token Verification", new
{
    controller = "Registration",
    action = "TokenVerification",
    ConfernceId = 0,
    TokenType = "0",
    TokenId = "0",
    Email = "0"
})

它会生成 - /Registration/TokenVerification/0/0/0/0