2

我创建了自定义ActionResult(简化):

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}"}

我究竟做错了什么?

4

1 回答 1

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 对象: 样本

于 2013-10-11T15:14:28.077 回答