我有一个方法最初返回一个HttpResponseMessage
我想将其转换为返回IHttpActionResult
.
我的问题是当前的代码正在使用 JSON.Net 来序列化复杂的通用树结构,它可以很好地使用自定义JsonConverter
我写的(代码运行良好)。
这是它返回的内容:
string json = NodeToJson(personNode);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(json, Encoding.UTF8, "application/json");
return response;
NodeToJson 方法是自定义转换器发挥作用的地方......
private static string NodeToJson(Node<Person> personNode) {
var settings = new JsonSerializerSettings {
Converters = new List<JsonConverter> { new OrgChartConverter() },
Formatting = Formatting.Indented
};
return JsonConvert.SerializeObject(personNode, settings);
}
请注意,这会返回一个string
,格式为 JSON。
如果我把它切换到IHttpActionResult
,无论我尝试什么,它似乎都会失败。我可以离开它(它有效),但我应该为此使用最佳实践并且IHttpActionResult
似乎是我应该使用的。
我已经尝试过return Json(json);
但这会导致无效的、无法解析的 JSON,大概是因为它试图进行双重转换?
return Ok(json);
结果 JSON 字符串被包装在 XML 中。
这样做的正确方法是什么?
EDIT:
除了这个特定方法之外,我现在已成功将该项目中的每个方法转换为使用 IHttpActionResult 。
它是通用树到 JSON 的序列化。无论我尝试什么方法,我都会返回无效的 JSON。这HttpResponseMsessage
方法工作正常,但我无法获取有效的 JSONIHttpActionResult
.