Ajax請求數據響應格式,一個醒目組必須是同意的,前端才知道怎麼應付,還有很多其他情況,比如異常了,有ExceptionFilter,按照固定格式返回,比如沒有許可權,Authorization,按照固定格式返回。 Http請求的本質: 請求--應答式,響應可以那麼豐富?不同的類型其實方式一樣的,只不 ...
Ajax請求數據響應格式,一個醒目組必須是同意的,前端才知道怎麼應付,還有很多其他情況,比如異常了,有ExceptionFilter,按照固定格式返回,比如沒有許可權,Authorization,按照固定格式返回。
Http請求的本質:
請求--應答式,響應可以那麼豐富?不同的類型其實方式一樣的,只不過有個ContenetType的差別,html--text/html、json--application/json、xml/application/xml、js--application/JavaScript、ico--image/x-icon、image/gif、image/jepg、image/png.....
這個等於是Http協議約定,Web框架和瀏覽器共同支持的。其實就是伺服器告訴瀏覽器如何處理這個數據,從頁面下載pdf或者頁面展示pdf靠的就是ContentType,application/pdf、application/octet-stream。
MVC各種Result的事,JsonResult實際上就是JsonResult,繼承ActionResult,然後重寫ExecuteResult方法,指定ContentType為application/json,然後將Data序列化成字元串寫入stream,我們可以隨意擴展,只需要把數據放到response,指定好ContentType
ContentType對照表:http://tool.oschina.net/commons
/// <summary> /// 返回ActionResult--MVC框架會執行其ExecuteResult方法--- /// </summary> /// <returns></returns> public JsonResult JsonResultIn() { return Json(new AjaxResult() { Result = DoResult.Success, DebugMessage = "這裡是JsonResult" }, JsonRequestBehavior.AllowGet); }
比如我們現在來擴展個NewtonJsonResult
public class NewtonJsonResult : ActionResult { private object Data = null; public NewtonJsonResult(object data) { this.Data = data; } public override void ExecuteResult(ControllerContext context) { HttpResponseBase response = context.HttpContext.Response; response.ContentType = "application/json"; response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(this.Data)); } }
調用的時候:
/// <summary> /// 返回ActionResult--MVC框架會執行其ExecuteResult方法--- /// </summary> /// <returns></returns> public NewtonJsonResult JsonResultNewton() { return new NewtonJsonResult(new AjaxResult() { Result = DoResult.Success, DebugMessage = "這裡是JsonResult" }); }
AjaxResult:
public class AjaxResult { public AjaxResult() { } public string DebugMessage { get; set; } public string PromptMsg { get; set; } public DoResult Result { get; set; } public object RetValue { get; set; } public object Tag { get; set; } } public enum DoResult { Failed = 0, Success = 1, OverTime = 2, NoAuthorization = 3, Other = 255 }View Code
自定義擴展XMLResult
/// <summary> /// 自定義擴展XML格式result /// </summary> public class XmlResult : ActionResult { private object _data; public XmlResult(object data) { _data = data; } public override void ExecuteResult(ControllerContext context) { var serializer = new XmlSerializer(_data.GetType()); var response = context.HttpContext.Response; response.ContentType = "text/xml"; serializer.Serialize(response.Output, _data); } }
public XmlResult XmlResult() { return new XmlResult(new AjaxResult() { Result = DoResult.Success, DebugMessage = "這裡是JsonResult" }); }
現在,我們不寫返回值,直接寫入stream
/// </summary> public void JsonResultVoid() { HttpResponseBase response = base.HttpContext.Response; response.ContentType = "application/json"; response.Write( Newtonsoft.Json.JsonConvert.SerializeObject(new AjaxResult() { Result = DoResult.Success, DebugMessage = "這裡是JsonResult" })); }