gpt4 book ai didi

c# - MVC 重定向结果

转载 作者:IT王子 更新时间:2023-10-29 04:29:05 25 4
gpt4 key购买 nike

我是 MVC 的新手,谁能告诉我 RedirectResult 的用途?

我想知道这之间有什么不同:

public ActionResult Index()
{
return new RedirectResult("http://www.google.com");
}

还有这个:

public RedirectResult Index()
{
return new RedirectResult("http://www.google.com");
}

最佳答案

它用于执行 HTTP redirect给定的网址。基本上它会在响应中发送 302 状态代码和 Location header ,以便客户端现在向这个新位置发出新的 HTTP 请求。

通常你会像这样使用它而不是显式调用构造函数:

public ActionResult Index()
{
return Redirect("http://www.google.com");
}

就您的两个代码片段之间的区别而言,与其说是 MVC 相关,不如说是 C# 问题。事实上RedirectResult源自 ActionResult所以两者都是有效的语法。我个人更喜欢第一个,因为您可以决定更改此重定向以返回 View :

public ActionResult Index()
{
return View();
}

并且如果您明确指定返回类型是 RedirectResult 而不是 ActionResult 您现在必须将其修改为 ViewResult(可能没什么大不了的,但这是你必须做的额外步骤)。

关于c# - MVC 重定向结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4387127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com