我撥打RedirectToAction
的行爲如同RedirectToActionPermanent
。也就是說,URL正在改變,而不是簡單地顯示不同的視圖。RedirectToAction正在更改URL
編輯:現在我想想,
RedirectToAction
通常作爲一個永久重定向。如在,這可能是正確的行爲。在下面的代碼,如果ModelState
是有效的,給予用戶302重定向回索引。但是,那麼RedirectToActionPermanent
有什麼意義?
重定向用於HTTP錯誤。我有我的Web.config文件設置爲指向在HttpErrorsController
錯誤某些操作方法。這可以完美地工作,包括按預期顯示臨時重定向。 (https://localhost/ThisPageDoesntExist
顯示錯誤頁面,但URL保持不變)
返回HttpStatusCodeResult
或拋出HttpException
均按預期工作。但是,如果我試圖通過使用RedirectToAction
臨時重定向到錯誤操作方法,該視圖仍可正確顯示,但URL會發生變化,例如, https://localhost/HttpErrors/404
。
HttpErrorsController.cs
private ViewResult ErrorView(HttpStatusCode httpStatusCode, string shortDesc, string longDesc)
{
Response.StatusCode = (int)httpStatusCode;
return View("HttpError", new HttpErrorViewModel(httpStatusCode, shortDesc, longDesc));
}
[ActionName("404")]
public ActionResult Error404()
{
return ErrorView(HttpStatusCode.NotFound, "Not Found",
"The requested resource could not be found.");
}
// Other identical methods for each error
ItemController.cs
public ActionResult HttpError(HttpStatusCode status)
{
return RedirectToAction(((int)status).ToString(), "HttpErrors");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ItemViewModel viewModel)
{
if (!Request.IsAjaxRequest())
{
return HttpError(HttpStatusCode.NotAcceptable);
}
if (ModelState.IsValid)
{
db.Items.Add(pm);
db.SaveChanges();
return RedirectToAction("Index");
}
return PartialView("_Create", viewModel);
}
自寫上面的,我已經意識到我可能會更好過只是拋出一個HttpException
,因此,它也被逮住由ELMAH,但我仍然很困惑上述行爲。
是的,我張貼的'RedirectToAction'始終做到這一點之後實現的。看到我的編輯,關於這一點。至於直接返回視圖,我想過,但我不知道如何從另一個控制器調用該操作方法。並且在'ItemController'中返回'View(「HttpError」)'會擊敗這一點。 – Sinjai
你可以使用一個自定義的錯誤處理程序屬性(繼承自'HandleErrorAttribute',它處理你的錯誤,並且在'OnException'方法中,你可以返回任何你想要的迴應。 – Shyju
據我所知,你仍然必須自己指定視圖這一點。 – Sinjai