Home > Net >  Httpclient () send asynchronous abnormal problems when a POST request
Httpclient () send asynchronous abnormal problems when a POST request

Time:11-19

Use the Httpclient () to send a POST request to get the Token, part of the program is as follows:
 
Public async Task GetAccessTokenAsync ()
{
If (SubscriptionKey==string. The Empty) return string. The Empty;

//Re - use the cached token if there is one.
If ((DateTime. Now - storedTokenTime) & lt; TokenCacheDuration)
{
Return storedTokenValue;
}

Using (var client=new HttpClient ())
Using (var request=new HttpRequestMessage ())
{
Request. The Method=HttpMethod. Post;
Request. RequestUri=ServiceUrl;
Request. The Content=new StringContent (string. The Empty);
Request. Headers. TryAddWithoutValidation (OcpApimSubscriptionKeyHeader, enclosing SubscriptionKey);
Client. The Timeout=TimeSpan. FromSeconds (2);

Var response=await client. SendAsync (request);
Enclosing RequestStatusCode=response. StatusCode;
The response. EnsureSuccessStatusCode ();
Var token=await the response. The content. ReadAsStringAsync ();
StoredTokenTime=DateTime. Now;
StoredTokenValue="https://bbs.csdn.net/topics/Bearer" + token;
Return storedTokenValue;
}
}

In the process of debugging, found that the program runs to
Var response=await client. SendAsync (request); , will not be able to continue running down, in the process of neither wrong nor any other news, according to
I am a rookie, has been the problem with two weeks, looking forward to Daniel, please advise,

CodePudding user response:

Await the back of the code is to wait SendAsync success will perform the ah

CodePudding user response:

reference 1st floor Poopaye response:
await the back of the code is to wait SendAsync success will perform the ah

It's has not been successful? So how can I check where is the problem? May probably is the problem?

CodePudding user response:

The building Lord solved? I also met the same problem,

CodePudding user response:

Try catch

CodePudding user response:

The
reference 4 floor woainixinxin521 reply:
try catch

Try catch no flash back directly without any exception

CodePudding user response:

reference 5 floor Fresochoi reply:
Quote: refer to 4th floor woainixinxin521 response:

Try catch

Try catch no flash back directly without any exception

How to flash back directly don't understand

CodePudding user response:

Excuse me, solved yet? My request is to await then thread is blocked

CodePudding user response:

I always don't know the meaning of the asynchronous HTTP...

You access token is eventually to once again to request other interface.

In the call. Also wait. Doesn't it feel...
  •  Tags:  
  • C#
  • Related