添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Why I get http status code = 0 in my case iStatusCode occasionally?, what I missed from my codes below?

ASP.NET Core 6

 HttpResponseMessage httpRes = _httpClient.GetAsync(url).Result;
 iStatusCode = (int)httpRes.StatusCode;
 if (httpRes.IsSuccessStatusCode)
     string _res = httpRes.Content.ReadAsStringAsync().Result;
												

According to your other thread, you're making a call to a 3rd party API. Zero is not a standard status code but zero is the default value of an int. Perhaps the 3rd party service has documentation that explains what zero means. Or maybe there is something else wrong with your code. How do you know zero is returned? I don't see any logging.

FYI, calling .Result blocks a thread. You should use await.

Asynchronous programming with async and await

Asynchronous programming scenarios

to below, need your advice.

thank you

HttpResponseMessage httpRes = _httpClient.GetAsync(url).Result;
httpRes.EnsureSuccessStatusCode();
iStatusCode = (int)httpRes.StatusCode;
if (httpRes.IsSuccessStatusCode)
    string _res = httpRes.Content.ReadAsStringAsync().Result;
Save2LogTable(url, iStatusCode);
        HttpResponseMessage httpRes = _httpClient.GetAsync(url).Result; 
        httpRes.EnsureSuccessStatusCode(); 
        iStatusCode = (int)httpRes.StatusCode; 
        if (httpRes.IsSuccessStatusCode) 
           string result = httpRes.Content.ReadAsStringAsync().Result; 
           // do some stuffs to read result value and set _res value and return it.
        SaveLog(url, iStatusCode); 
    catch (Exception e)             { SaveErr("here, " + e.ToString(); } 
    return await Task.FromResult(_res); 
												

My best guess is the client code that calls the test() method is not awaiting the results. The main thread is allowed to run running through the test() method. iStatusCode is zero because iStatusCode is initialized to zero.

Please read the link in my last post to learn the async/await pattern. Then apply the pattern to your code. I'm pretty sure using the async/await pattern will fix this problem.

Does an exception get thrown when 0 is the status code? It looks like the only scenario when iStatusCode isn't overridden is when there's an exception.

Edit: The snippet you posted has this line above the line that you set iStatusCode:

httpRes.EnsureSuccessStatusCode();

Because the line above will throw an exception if there's a non-success status code, regardless of the status code iStatusCode will retain the value of 0. You could move that line below the line that sets iStatusCode, then at least you'll have the original status code to go off.