C# 下封装好的一个类 get和post 请求,针对自己开发的WebAPI core 非常好用

   internal static class ServiceRequest
   {
       public static string APIurl { get; set; } = "https://localhost:5001"; //   

       public static async Task<(string result,string error)> SendGetRequest(string url)
       {

           string result = string.Empty;
           string error = string.Empty;

           using (HttpClient client = new HttpClient())
           {
               HttpResponseMessage response = await client.GetAsync(APIurl + url);
               if (response.IsSuccessStatusCode)
               {
                   string responseContent = await response.Content.ReadAsStringAsync();
                   response.Content.Dispose();
                   response.Dispose();
                   result = responseContent;
               }
               else
               {
                   error = "Error: " + response.StatusCode;
               }
           }

           return (result, error);
       }

       public static async Task<string> SendPostRequest(string url, string jsonContent)
       {
           using (HttpClient httpClient = new HttpClient())
           {
               StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

               HttpResponseMessage response = await httpClient.PostAsync(APIurl + url, content);

               if (response.IsSuccessStatusCode)
               {
                   string responseContent = await response.Content.ReadAsStringAsync();
                   response.Content.Dispose();
                   response.Dispose();
                   return responseContent;
               }
               else
               {
                   return $"Error: {response.StatusCode}";
               }
           }
       }
   }

一边学习 一边实践 一边提升

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值