Detailed Explanation of mvc Redirection Mode

  • 2021-09-11 19:55:24
  • OfStack

In this article, we share several ways of mvc redirection for your reference. The specific contents are as follows

Add a simple route to RouteConfig


// Add a route 
 routes.MapRoute(
 name: "Article",
 url: "Detial/{id}",
 defaults: new { controller = "Article", action = "Detial", id = UrlParameter.Optional },
 constraints: new { id = @"\d+" }
 //namespaces: new string[] { }
);

302 Redirection


public ActionResult UrlTest1()
 {//302
  return Redirect("/Article/Detial/1");
 }
 public ActionResult UrlTest2()
 {//302
 return RedirectToAction("Detial", "Article", new System.Web.Routing.RouteValueDictionary(new { id = 2 }));
 //return RedirectToAction("Detial", "Article",new { id = 1});
 }
 public ActionResult UrlTest3()
 {//302
 return RedirectToRoute("Article", new System.Web.Routing.RouteValueDictionary(new { id = 3 }));
 //return RedirectToRoute("Article", new { id = 1 });
}


301 redirection


  

public ActionResult UrlTest4()
 {//301
   return RedirectPermanent("/Article/Detial/4");
  }

  public ActionResult UrlTest5()
  {//301
   return RedirectToActionPermanent("Detial", "Article", new System.Web.Routing.RouteValueDictionary(new { id = 5 }));
   //return RedirectToActionPermanent("Detial", "Article", new { id = 1 });
  }

  public ActionResult UrlTest6()
  {//301
   return RedirectToRoutePermanent("Article", new System.Web.Routing.RouteValueDictionary(new { id = 6 }));
   //return RedirectToRoutePermanent("Article", new { id = 1 });
  }

You can also set it yourself


 public ActionResult UrlTest7()
 {// Settable 
  return new RedirectToRouteResult("Article", new System.Web.Routing.RouteValueDictionary(new { id = 7 }), false) { };
 }
 public ActionResult UrlTest8()
 {// Settable 
  return new RedirectResult("/Article/Detial/8", false);
 }

Note that specifying a different view in View () is not a redirect


 public ActionResult UrlTest9()
 {//200
  return View("Detial", null, new { id = 9 });
 }

The methods in snippet 2 and snippet 3 are returned to the client as in snippet 4 and finally as Response. Redirect methods


Related articles: