首页 > 解决方案 > 如何继续等待 API 请求响应值完成 ASP .Net Core MVC

问题描述

我有使用 Azure 服务管理 API 的带有多个外部 api 请求的 asp .net core mvc 应用程序。https://docs.microsoft.com/en-us/rest/api/resources/providers/register#code-try-0从这个 api 请求注册任何命名空间。但它有更多的时间来完成。最初,它的响应 json 属性值为“未注册”,在上述 POST 请求发送其值设置为“注册”之后。它需要 2 到 3 分钟才能完成。最后将响应值设置为“已注册”。

HttpClient client = new HttpClient();
HttpRequestMessage request2 = new HttpRequestMessage(HttpMethod.Post, String.Format(Constants.MicrosoftManagedProviderRegisterApi, subscription));
                    request2.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

                    // Ensure a successful response
                    HttpResponseMessage response2 = await client.SendAsync(request2);
                    response2.EnsureSuccessStatusCode();

这就是我发送 API 请求的方式。我想知道我应该如何在控制器内部等待,直到响应 json 属性值设置为“已注册”。有什么简单的方法可以实现这一点吗?

请参阅下面的响应类型。

{
  "id": "/subscriptions/***/providers/Microsoft.ManagedServices",
  "namespace": "Microsoft.ManagedServices",
  "authorization": "",
  "resourceTypes": [],
  "registrationState": "Unregistered",
  "registrationPolicy": "RegistrationRequired"
}

{
      "id": "/subscriptions/***/providers/Microsoft.ManagedServices",
      "namespace": "Microsoft.ManagedServices",
      "authorization": "",
      "resourceTypes": [],
      "registrationState": "Registering",
      "registrationPolicy": "RegistrationRequired"
}

{
      "id": "/subscriptions/***/providers/Microsoft.ManagedServices",
      "namespace": "Microsoft.ManagedServices",
      "authorization": "",
      "resourceTypes": [],
      "registrationState": "Registered",
      "registrationPolicy": "RegistrationRequired"
}

标签: c#asp.net-mvcazureasp.net-core

解决方案


HttpClient有一个名为的属性Timeout,默认情况下设置为100秒,使用这个:

client.Timeout = TimeSpan.FromMinutes(4);


推荐阅读