我使用的是Asp.NET MVC5
我有以下控制器
public class AController : Controller {
public ActionResult ActionA(int param1, int param2) {
return Content("Whatever") ;
}
}将url /B/ActionB?p1=5&p2=9重定向到/A/ActionA?param1=p1¶m2=p2的正确方法是什么?
编辑:我尝试了以下方法,但在转换参数时遇到困难
public class AController : Controller {
[Route("/B/ActionB")]
public ActionResult ActionA(int param1, int param2) {
return Content("Whatever") ;
}
}发布于 2017-10-12 16:34:17
重定向的正确方法是使用RedirectToAction
// URL /B/ActionB?p1=5&p2=9
public class BController : Controller {
public ActionResult ActionB(int p1, int p2) {
return RedirectToAction("ActionA", "A", new { param1 = p1, param2 = p2 });
}
}
// URL /A/ActionA?param1=5¶m2=9
public class AController : Controller {
public ActionResult ActionA(int param1, int param2) {
return Content("Whatever") ;
}
}但请注意,调用/B/ActionB?p1=5&p2=9将到达ActionB,然后MVC将响应一个302状态代码,告诉浏览器获取URL /A/ActionA?param1=5¶m2=9。因此,它将到服务器的1次往返变成了2次。
从应用程序设计的角度来看,除非您有某些特定的原因需要更改用户浏览器中的/A/ActionA?param1=5¶m2=9,否则直接转到URL会更有意义。
如果您的目标是将所有流量从BController.ActionB转移到AController.ActionA,因为您正在应用程序中替换它,那么您应该执行301重定向。这最好由IIS URL重写模块来处理。
<?xml version="1.0"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Redirect /B/ActionB?p1=5&p2=9 to /A/ActionA?param1=p1¶m2=p2" stopProcessing="true">
<match url="^B/ActionB?p1=(\d+)&p2=(\d+)" />
<action type="Redirect" url="A/ActionA?param1={R:1}¶m2={R:2}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
<httpProtocol>
<redirectHeaders>
<!-- This is to ensure that clients don't cache the 301 itself - this is dangerous because the 301 can't change when put in place once it is cached -->
<add name="Cache-Control" value="no-cache"/>
</redirectHeaders>
</httpProtocol>
</system.webServer>
</configuration>请注意,如果查询字符串参数是可选的,或者可能以相反的顺序出现,则需要添加额外的规则来涵盖这些情况。
或者,您可以使用MVC中的路由进行301重定向。这里有一个示例here,不过需要对它进行修改,以便从请求中提取查询字符串参数,并使用不同的名称将它们传递给接收端。
https://stackoverflow.com/questions/46704604
复制相似问题