1. 程式人生 > 實用技巧 >[C#] HttpClient的一點思考

[C#] HttpClient的一點思考

幾個錯誤的思考,不知道是否正確。

 public static async Task<HttpResponse<T>> HttpPostTaskAsync<T>(string url, object q)
        {
            try
            {
                StringContent content = new StringContent(JsonConvert.SerializeObject(q, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var ret = await _HC.PostAsync(url, content);
                if (!ret.IsSuccessStatusCode)//Api相關錯誤,重試無效,理論上應該在開發階段全部排除
                    return new HttpResponse<T>(false, ret.ReasonPhrase);
                var msg = await ret.Content.ReadAsStringAsync();
                return new HttpResponse<T>(true, msg);

            }
            catch (HttpRequestException ex)//網路錯誤,可以重試
            {
                throw;

            }
            catch (System.Exception ex) //其他錯誤,馬上修改
            {
                throw;

            }
        }