我打给RedirectToAction的电话就像RedirectToActionPermanent一样。也就是说,URL正在被更改,而不是仅仅显示一个不同的视图。
编辑:现在我考虑一下,
RedirectToAction通常充当永久的重定向。正如所述,这可能是正确的行为。在下面的代码中,如果ModelState是有效的,则给用户302个重定向回到索引。但是,RedirectToActionPermanent的意义是什么呢?
重定向是针对HTTP错误的。我的Web.config设置为将错误指向HttpErrorsController中的某些操作方法。这是完美的工作,包括显示临时重定向,如预期。(https://localhost/ThisPageDoesntExist显示错误页面,但网址保持不变)
返回一个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 errorItemController.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捕获,但是我仍然对上面描述的行为感到非常困惑。
发布于 2017-08-24 19:30:40
RedirectToAction方法用location头值向浏览器发送302个响应,新的url和浏览器将向这个新的url发出一个全新的http请求。所以你看到的是预期的行为。
如果您不想重定向,但希望保持url的原样,请不要返回RedirectResult,根据需要返回视图结果。
RedirectToActionPermanent方法将301个移动的永久响应发送回客户端。当您将一个页面移动到另一个页面(删除旧页并创建一个具有不同url的新页面时),并且希望客户端知道这一点,这样他们就可以在将来使用新的url了,这通常很有用。考虑谷歌搜索引擎,改变链接到你的新网页,并显示在搜索结果。
https://stackoverflow.com/questions/45869468
复制相似问题