【问题标题】:Web service calling another webserviceWeb 服务调用另一个 Web 服务
【发布时间】:2018-02-07 04:19:57
【问题描述】:

所以我有一个数据库,当在其中找不到值时会填满,基本上是一个用 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 方法/函数有关,但我似乎无法找到更好的解决方案来解决我的问题。任何帮助将不胜感激!

【问题讨论】:

  • AddPersonAsyncCompleteAsync 实际上是异步的吗?因为你不等待他们。
  • 等待完整的异步,addPersonasync 是异步的,但我将其同步进行测试,但这似乎不是真正的问题。

标签: c# web-services async-await httpclient


【解决方案1】:

您的异常处理非常错误。现在你吞下了异常。此外,您可以使用致命异常来执行此操作。这是异常处理的致命罪过,可以很容易地解释任何奇怪的行为。

在发生致命异常后,您的程序应始终关闭。忽略它们只会导致更多无法调试甚至无法预测的后续错误。

您应该阅读正确的异常处理。以下是我经常链接的两篇文章:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 2011-02-16
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多