我创建了自定义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}"}
我究竟做错了什么?
使用自定义格式化程序解决了此问题(简化了发布更少的代码)
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对象:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句