读取/解析WEB API 2 IHttpActionResult响应的最佳方式是什么
本文关键字:响应 最佳 方式 是什么 IHttpActionResult 解析 WEB API 读取 | 更新日期: 2023-09-27 17:57:54
我有以下web api方法:
public IHttpActionResult Get(int id)
{
var person = _personRepository.GetPersonByID(id);
if (person == null)
return NotFound();
return Ok<Person>(person);
}
以及以下客户端调用方法:
var data = default(IEnumerable<T>);
var response = _client.GetAsync(relativeUri).Result;
response.EnsureSuccessStatusCode(); // Throw on error code.
if (response.IsSuccessStatusCode)
{
//string dataString = response.Content.ReadAsStringAsync().Result;
data = response.Content.ReadAsAsync<IEnumerable<T>>().Result;
}
else
{
//return response status code/reason phrase
}
ReadAsAsync调用完成后,数据变量指示类型为T的集合,该集合的计数与返回的行匹配,但所有对象(元素)都具有空值属性或为空。属性中未填充实际值。
Fiddler显示JSON字符串。甚至,ReadAsStringAsAsync()方法也返回JSON字符串。
有没有更好的方法可以使用ReadAsXXX()方法将JSON解析为T类型?
谢谢,
-Jignesh
我只是想更新一下,我已经找到了我所面临问题的根本原因。
我提到的代码示例实际上是调用webapi方法的正确方法。
在我的例子中,JSON字符串在服务器端使用Camel Casing格式,在客户端使用默认格式。
这是导致问题的服务器端代码:
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
一旦这个被移除,它就开始工作。
显然,ReadAsAsync方法找不到匹配的属性,因此所有值都被删除。
谢谢,
-Jignesh