在Asp.net Core之前所有的Action返回值都是ActionResult,Json(),File()等方法返回的都是ActionResult的子类。并且Core把MVC跟WebApi合并之后Action的返回值体系也有了很大的变化。
ActionResult类
ActionResult类是最常用的返回值类型。基本沿用了之前Asp.net MVC的那套东西,使用它大部分情况都没问题。比如用它来返回视图,返回json,返回文件等等。如果是异步则使用Task。
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult MyFile()
{
return File(new byte[] { }, "image/jpg");
}
public ActionResult MyJson()
{
return Json(new { name = "json" });
}
public ActionResult Ok()
{
return Ok();
}
}
IActionResult接口
ActionResult类实现了IActionResult接口所以能用ActionResult的地方都可以使用IActionResult来替换。同样异步的话使用Task包起来做为返回值。
public class ITestController : Control