ASP.NET Core MVC 重定向 Redirect 整理

我們常使用的跳轉頁面有兩種方式:301 和 302 重定向,兩者皆是伺服器告訴瀏覽器網址已經變更,需要跳去新的地方瀏覽。 而 307 跟 308 和 301 跟 302 的差別就是 7 和 8 會使用原本的 HttpMethod,而 1 跟 2 都只能是 Get

301 重定向 - 指定 URL

使用 Get 方法跳轉到指定 URL
    
    [HttpGet]
    public IActionResult Index()
    {
        return RedirectPermanent("~/User/Data");
    }
    

302 重定向 - 指定 URL

使用 Get 方法跳轉到指定 URL
    
    [HttpGet]
    public IActionResult Index()
    {
        return Redirect("~/User/Data");
    }
    

302 重定向 - 指定 Action

使用 Get 方法跳轉到指定 Action 的 URL
    
    [HttpGet]
    public IActionResult Index()
    {
        return RedirectToAction(nameof(Data));
    }
    
    [HttpGet]
    public IActionResult Data()
    {
        return View();
    }
    
    

307 重定向 - 指定 URL 和相同的 HttpMethod

使用和來源相同 Http Method 跳轉到指定 URL (例如 Post)
    
    [HttpPost]
    public IActionResult Index()
    {
        return RedirectPreserveMethod("~/User/Data");
    }
    
    

308 重定向 - 指定 URL 和相同的 HttpMethod

使用和來源相同 Http Method 跳轉到指定 URL (例如 Post)
    
    [HttpPost]
    public IActionResult Index()
    {
        return RedirectPermanentPreserveMethod("~/User/Data");
    }
    
    

留言