C# 重定向操作和重定向路由

C# 重定向操作和重定向路由,c#,.net,asp.net-mvc,asp.net-mvc-routing,C#,.net,Asp.net Mvc,Asp.net Mvc Routing,在我的网页1控制器中,我想重定向到网页2,传递2个变量 我尝试使用RedirectToRoute,但无法使其工作;显示错误的URL。 然后我切换到使用重定向操作 我的代码: 路由 routes.MapRoute( "CreateAdditionalPreviousNames", // Route name "Users/{controller}/{action}/{userId}/{applicantId}", // URL with parameters new { c

在我的网页1控制器中,我想重定向到网页2,传递2个变量

我尝试使用RedirectToRoute,但无法使其工作;显示错误的URL。 然后我切换到使用重定向操作

我的代码:

路由

routes.MapRoute(
    "CreateAdditionalPreviousNames", // Route name
    "Users/{controller}/{action}/{userId}/{applicantId}", // URL with parameters
    new { controller = "UsersAdditionalPreviousNames", action = "Index", userId = UrlParameter.Optional, applicantId = UrlParameter.Optional } // Parameter defaults
);
重定向到操作(哪个有效)

重定向路由(不工作)


哦,还有一件事,你能让参数成为必需的,而不是可选的吗?如果是这样,怎么做?

省略参数默认值以使参数成为必需的:

    routes.MapRoute(
    "CreateAdditionalPreviousNames", // Route name
    "Users/{controller}/{action}/{userId}/{applicantId}", // URL with parameters
    new { controller = "UsersAdditionalPreviousNames", action = "Index" }
);
对于路由重定向,请尝试以下操作:

return RedirectToRoute(new 
{ 
    controller = "UsersAdditionalPreviousNames", 
    action = "Index", 
    userId = user.Id, 
    applicantId = applicant.Id 
});
我从史蒂夫·桑德森那里学到的另一个习惯是不给你的路线命名。每个路由可以有一个空名称,这使您可以显式指定所有参数:

    routes.MapRoute(
    null, // Route name
    "Users/{controller}/{action}/{userId}/{applicantId}", // URL with parameters
    new { controller = "UsersAdditionalPreviousNames", action = "Index" }
);

如果他们不提供参数,您预计会发生什么?是的,这是可能的,但是将会发生404错误,或者类似的事情。这就是你想要的吗?谢谢你,这很有效。我只是想知道为什么我的RedirectToRoute版本不起作用,因为我正在跟踪重载方法的签名……有什么想法吗?Thanks@user1079925,就像我说的,我养成了不命名路线的习惯,所以我从不使用带有路线名称的重载。希望其他人能回答,谁能告诉你哪里出了问题。这可能是不给路线命名的原因之一,这个习惯对我来说是有好处的。好吧……我将带领你远离路线命名——看起来这是一种阻碍,而不是一种帮助。这并不能回答问题中描述的问题的解决方案,那么这怎么能被标记为一个可接受的答案呢
return RedirectToRoute(new 
{ 
    controller = "UsersAdditionalPreviousNames", 
    action = "Index", 
    userId = user.Id, 
    applicantId = applicant.Id 
});
    routes.MapRoute(
    null, // Route name
    "Users/{controller}/{action}/{userId}/{applicantId}", // URL with parameters
    new { controller = "UsersAdditionalPreviousNames", action = "Index" }
);