点关注不迷路

Max

.Net中通过HttpClient发送Delete请求附带Body参数

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;
            }
        }

 

posted @ 2021-10-13 16:32  Max麦克斯  阅读(547)  评论(0编辑  收藏  举报