[英]What's the best way to properly consume one of two “successful” responses from the same endpoint on a web api?
[英]What is the best way of reading/parsing WEB API 2 IHttpActionResult responses?
我有以下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字符串。
是否有更好的方法使用ReadAsXXXX()方法之一将JSON解析为T类型?
谢谢,
-Jignesh
我只是想更新一下,我已经找到了所面临问题的根本原因。
我提到的代码示例实际上是调用Web api方法的正确方法。
在我的情况下,JSON字符串在服务器端和客户端的Camel Casing中格式化,使用了默认格式。
这是导致问题的服务器端代码:
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
一旦将其删除,它便开始工作。
显然,ReadAsAsync方法找不到匹配的属性,因此所有值都将被删除。
谢谢,
-Jignesh
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.