https://blog.csdn.net/sundna/article/details/91511745
ActionResult是控制器方法执行后返回的结果类型,控制器方法可以返回一个直接或间接从ActionResult抽象类继承的类型,如果返回的是非ActionResult类型,控制器将会将结果转换为一个ContentResult类型。默认的ControllerActionInvoker调用ActionResult.ExecuteResult方法生成应答结果。
ActionResult 类图:
各种Result说明:
Result的封装:
除了通过new对象返回结果外,还可以使用封装后的方法;
public IActionResult Result1()//实例化对象 { JsonResult result = new JsonResult(new { name = "kxy1" }); return result; } public IActionResult Result2()//封装方法 { return Json(new { name = "kxy2" }); }
扩展ActionResult
下例将实现一个XmlResult
类型,用于返回XML
应答内容:
public class XmlResult : ActionResult { public XmlResult(Object data) { this.Data = data; } public Object Data { get; set; } public override void ExecuteResult(ControllerContext context) { if (Data == null) { new EmptyResult().ExecuteResult(context); return; } context.HttpContext.Response.ContentType = "application/xml"; using (MemoryStream ms = new MemoryStream()) { XmlSerializer xs = new XmlSerializer(Data.GetType()); xs.Serialize(ms, Data); ms.Position = 0; using (StreamReader sr = new StreamReader(ms)) { context.HttpContext.Response.Output.Write(sr.ReadToEnd()); } } } }