返回RedirectToAction VS回报行动
问题描述:
在我的web应用程序有一个叫做动作,即,取决于值,或者返回另一个动作或执行当前操作:返回RedirectToAction VS回报行动
public async Task<ActionResult> MyAction(int id)
{
bool someValue = AnyClass.GetSomeValue(); // doesn't matter what value: it's a boolean
if (someValue)
{
// should I:
return RedirectToAction("MyOtherAction", new {id = id});
// or should I:
return await MyOtherAction(id);
}
// do something here
return View();
}
public async Task<ActionResult> MyOtherAction(int id)
{
// do something else here
return View();
}
所以我应该在第一时间行动工作与
RedirectToAction("MyOtherAction", new {id = id});
或更好
return await MyOtherAction(id);
切换到其他操作?最后,他们俩都不一样吗?
答
两者之间的区别在于用户最终将在浏览器的地址栏中看到的内容。
使用return RedirectToAction("MyOtherAction", new {id = id});
您正在生成HTTP重定向,这意味着如果其他操作具有路由/my-other-action
,用户将最终在其地址栏中看到它,并且它将成为浏览器历史记录中的新条目。
另一方面,如果您的确做了return await MyOtherAction(id);
,则MyOtherAction
的结果将作为用户访问的当前URL(例如/my-action
)的结果呈现。
以上任何一种方法都是有效的,因此您需要确定您希望网站的用户拥有哪些这些体验。