Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MVC重定向结果_C#_Asp.net Mvc - Fatal编程技术网

C# MVC重定向结果

C# MVC重定向结果,c#,asp.net-mvc,C#,Asp.net Mvc,我是MVC新手,有人能告诉我重定向结果的用途吗 我想知道这两者之间有什么不同: public ActionResult Index() { return new RedirectResult("http://www.google.com"); } 这是: public RedirectResult Index() { return new RedirectResult("http://www.google.com"); } 它用于执行对给定url的访问。基本上,它将在响应中发

我是MVC新手,有人能告诉我重定向结果的用途吗

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

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

public RedirectResult Index()
{
    return new RedirectResult("http://www.google.com");
}
它用于执行对给定url的访问。基本上,它将在响应中发送302状态代码和位置头,以便客户机现在向这个新位置发出一个新的HTTP请求

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

public ActionResult Index()
{
    return Redirect("http://www.google.com");
}
就两段代码之间的差异而言,这更多的是C问题,而不是MVC相关的问题。事实上,它们都是有效的语法。就个人而言,我更喜欢第一个,因为您可以决定更改此重定向以返回视图:

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

如果您明确指定返回类型为
RedirectResult
而不是
ActionResult
,则现在必须将其修改为
ViewResult
(可能没什么大不了的,但这是您必须执行的附加步骤).

两者基本相同。主要概念是所有结果都源自acion结果


因此,如果将来您想要更改返回类型,那么可以使用ActionResult

谢谢,但我知道RedictResult源于ActionResult,但还有什么不同吗?当我们应该重新运行RedirectResult而不是Action Result时,
ActionResult
是一个抽象类,因此您永远无法返回它。您总是返回派生类,如ViewResult、RedirectResult、JsonResult、FileResult、JavaScriptResult、ContentResult,具体取决于您希望控制器操作执行的操作(呈现视图、重定向到另一个url、返回JSON格式的数据、下载文件等)。就您的操作方法的签名而言,出于我在回答中提到的原因,我建议您始终使用
ActionResult
作为返回类型。