如何持续等待API请求响应值完成ASP.Net核心MVC



我有asp.net核心mvc应用程序,使用Azure Service Management api有多个外部api请求。https://learn.microsoft.com/en-us/rest/api/resources/providers/register#code-try-0从这个api请求注册任何命名空间。但它需要更多的时间来完成。最初,它的响应json属性值是"Unregistered",在上面的POST请求之后,将其值设置为"Registering"。它需要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"
}

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

client.Timeout = TimeSpan.FromMinutes(4);

正如上面评论中提到的,在控制器中等待这么长时间是个坏主意。但是,由于需要等待那么长时间,我将提供一个实现这一点的逻辑:

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);
HttpResponseMessage response2 = null;
while (!IsRegistered(response2))
{
response2 = await client.SendAsync(request2).ConfigureAwait(false);
}

IsRegistered方法逻辑(添加更多检查(:

private Task<bool> IsRegistered(HttpResponseMessage response)
{
if (response != null)
{
var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(result))
{
serviceResponse = this.serializer.Deserialize<ServiceResponseSchema>(result);
if (string.Compare(serviceResponse.RegistrationState, "Registered") == 0)
{
return true;
}
}
}
return false;
}

我的理解是,你正在点击网址,直到你得到想要的回应。如果我的理解有误,请告诉我。

最新更新