2013-10-10 32 views
2

我創建的自定義ActionResult(簡體):在ASP.NET MVC自定義JSON結果

public class FastJSONResult : ActionResult 
{ 
    public string JsonData { get; private set; } 

    public FastJSONResult(object data) 
    { 
     JsonData = JSON.Instance.ToJSON(data); 
    } 

    public override void ExecuteResult(ControllerContext context) 
    { 
     HttpResponseBase response = context.HttpContext.Response; 
     response.ContentType = "application/json"; 
     response.Output.Write(JsonData); 
    } 
} 

而且用它從我的WebAPI控制器:,

public ActionResult GetReport() 
{ 
    var report = new Report(); 
    return new FastJSONResult(report); 
} 

現在的問題是儘管在FastJSONResult構造函數我的對象完美序列化,ExecuteResult永遠不會被調用,並在迴應我最終與對象類似

{"JsonData":"{my json object as a string value}"} 

我在做什麼錯?

+1

你響應看起來不錯,如果你使用'return Json(report,JsonRequestBehavior.AllowGet);'就會得到相同的響應。你嘗試過嗎? –

+0

@DZL好的,也許,但那不好,不是嗎? – Anri

+0

@DZL還有,我的觀點是,爲什麼'ExecuteResult'沒有被調用? – Anri

回答

1

與自定義格式(簡化後的代碼更少)

public class FastJsonFormatter : MediaTypeFormatter 
{ 
    private static JSONParameters _parameters = new JSONParameters() 
    { 
    public FastJsonFormatter() 
    { 
     SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); 
     SupportedEncodings.Add(new UTF8Encoding(false, true)); 
    } 

    public override bool CanReadType(Type type) 
    { 
     return true; 
    } 

    public override bool CanWriteType(Type type) 
    { 
     return true; 
    } 

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) 
    { 
     var task = Task<object>.Factory.StartNew(() => JSON.Instance.ToObject(new StreamReader(readStream).ReadToEnd(), type)); 
     return task; 
    } 

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) 
    { 
     var task = Task.Factory.StartNew(() => 
     { 
     var json = JSON.Instance.ToJSON(value, _parameters); 
     using (var w = new StreamWriter(writeStream)) w.Write(json); 
     }); 
     return task; 
    } 
} 

解決它在WebApiConfig.Register方法:

config.Formatters.Remove(config.Formatters.JsonFormatter); 
config.Formatters.Add(new FastJsonFormatter()); 

現在我正確地接收JSON對象: Sample