所以我有一个数据库,当它内部找不到值时就填满了,基本上是一个用C#编写的Web API,检查其中是否有值,如果它的null然后调用另一个Web服务将检索数据并将新记录插入数据库并将新创建的记录返回给用户。代码是这样的:
[HttpGet ("{idDocument}")]
public async Task<IActionResult> GetPerson (string idDocument)
{
// Get the person record from the database
var person = await repository.GetPersonAsync (idDocument);
// if the record does not exist, return not found
if (person == null)
{
Person newPerson = await GetNewPersonFromRemoteServer(idDocument);
var result = mapper.Map<Person, PersonResource>(newPerson);
return Ok(result);
}
// Map the record to a resource to return to user
var resource = mapper.Map<Person, PersonResource> (person);
// return record resource to user
return Ok (resource);
}
private async Task<Person> GetNewPersonFromRemoteServer(string id)
{
Person newPerson = new Person();
string address = "http://remoteservice.serv/?id=";
string fullAddress = address + id;
try
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(new Uri(fullAddress));
string responseMessage = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
Person newPerson = JsonConvert.Deserialize<Person>(responseMessage);
repository.AddPersonAsync(newPerson);
await uow.CompleteAsync();
return newPerson;
}
return newPerson;
}
}
catch (Exception ex)
{
return newPerson;
}
}
但是服务有时会工作,有时甚至会返回null,如果我执行远程服务,我会收到正确数据的响应。我相信它与嵌套的async / await方法/函数有关,但我似乎无法找到解决问题的更好方法。任何帮助将不胜感激!
答案 0 :(得分:0)
您的异常处理极为错误。现在你吞下了Exceptions。而且,你使用致命异常来做到这一点。这是异常处理的致命罪,可以很容易地解释任何奇怪的行为。
在致命异常之后,您的程序应始终关闭。忽略它们只会导致更多无法调试甚至无法预测的后续错误。
您应该阅读适当的异常处理。以下是我经常联系的两篇文章: