.Net中通過HttpClient傳送Delete請求附帶Body引數
阿新 • • 發佈:2021-10-13
private static async Task<TResult> DeleteData<TParam, TResult>(string url, TParam param) where TParam : class where TResult : class { try { var json = JsonConvert.SerializeObject(param, s_JsonSerializerSettings); s_Logger.LogInformation($"傳送請求到{url},傳送的資料為{json}"); using (var client = new HttpClient()) using (var request = new HttpRequestMessage(HttpMethod.Delete, url)) using (request.Content = new StringContent(json, Encoding.UTF8, "application/json")) {var httpResponse = await client.SendAsync(request).ConfigureAwait(false); if (httpResponse.IsSuccessStatusCode) { var responseBody = await httpResponse.Content.ReadAsStringAsync(); s_Logger.LogInformation($"請求完成,結果為“{responseBody}”"); return JsonConvert.DeserializeObject<TResult>(responseBody); } else { throw new Exception($"響應狀態為{httpResponse.StatusCode}"); } } } catch (Exception ex) { s_Logger.LogError(ex, $"請求失敗,錯誤為{ex.Message}"); return null; } }