The correct way to redirect is to use 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") ;
}
}
But do note that calling /B/ActionB?p1=5&p2=9
will reach ActionB
and then MVC will respond with a 302 status code telling the browser to fetch the URL /A/ActionA?param1=5¶m2=9
. So, it turns 1 round trip to the server into 2.
From an application design standpoint, it makes more sense to go directly to /A/ActionA?param1=5¶m2=9
unless you have some specific reason why you need to change the URL in the user's browser.
If your goal is to divert all traffic from BController.ActionB
to AController.ActionA
because you are replacing it in your application, you should do a 301 redirect. That is best handled by the IIS URL Rewrite Module.
<?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>
Do note that if the query string parameters are optional or could appear in reverse order, you will need to add additional rules to cover those cases.
Alternatively, you could use routing in MVC for the 301 redirects. There is an example here, although it would need to be modified to extract the query string arguments from the request and pass them to the receiving end using different names.