支援.net framework4.5.1,.net core2.0及以上

應用層需要引用包Kogel.Net,Nuget上可以下載安裝。

或者使用Nuget命令新增包

  1. Install-Package Kogel.Net

(一)註冊

如果是.netcore直接可以在啟動類中(Startup.cs)中註冊

  1. //註冊HttpClient
  2. services.AddKogelHttpClient();

其他環境直接

  1. //請求操作
  2. IHttpClient httpClient = new HttpClient();
  3.  
  4. //檔案訪問操作
  5. IFileClient fileClient = new FileClient();

(二)使用

get請求

  1. var responseText = httpClient.Get("https://www.baidu.com/");
  2. Console.WriteLine(responseText);

post請求

  1. var response = httpClient.Post("https://localhost:44370/api/basic/cost_info/get_list", new { cost_code = "837" }, accessToken);
  2. //response.StatusCode//狀態碼
  3. Console.WriteLine(response.Result);

指定型別返回

  1. var resultResponse = httpClient.Post<ResultResponse<PageList<GetCostInfoListReponse>>>("https://localhost:44370/api/basic/cost_info/get_list", new { cost_code = "837" }, accessToken);
  2. Console.WriteLine(JsonConvert.SerializeObject(resultResponse));

自定義請求

  1. //引數
  2. var jsonData = JsonConvert.SerializeObject(new { cost_code = "837" });
  3. var byteArr = Encoding.UTF8.GetBytes(jsonData);
  4.  
  5. //請求頭
  6. WebHeaderCollection header = new WebHeaderCollection();
  7. header.Add("Authorization", $"Bearer {accessToken}");
  8.  
  9. //開始請求
  10. var response = httpClient.Request(new KogelRequest
  11. {
  12. Method = "post",
  13. Url = "https://localhost:44370/api/basic/cost_info/get_list",
  14. ContentType = "application/json",
  15. PostDataType = PostDataType.Byte,
  16. PostDataByte = byteArr,
  17. Header = header
  18. });
  19. Console.WriteLine(response.Result);

(三)檔案操作

通過IFileClient操作,和IHttpClient同理

檔案下載

  1. string path = $"{Directory.GetCurrentDirectory()}\\abc.png";
  2. fileClient.Download("https://localhost:44370/files/abc.png", path);

檔案上傳

  1. string path = $"{Directory.GetCurrentDirectory()}\\abc.png";
  2. var resultResponse = fileClient.Upload("https://localhost:44370/api/file/uplpad?suffix=png", path, accessToken);
  3. Console.WriteLine(JsonConvert.SerializeObject(resultResponse));

(四)使用Aop檢視執行的請求

可以監控請求執行的前後,並且只會作用於當前上下文

  1. //aop監聽請求(只會作用於當前上下文)
  2. //執行前
  3. HttpBase.Aop.OnExecuting += (KogelRequest request) =>
  4. {
  5. //請求的url
  6. var url = request.Url;
  7. //請求的引數
  8. var param = request.PostDataByte;
  9. //其他HttpWebRequest引數基本都有
  10. };
  11.  
  12. //執行後
  13. HttpBase.Aop.OnExecuted += (KogelRequest request) =>
  14. {
  15. //請求的url
  16. var url = request.Url;
  17. //請求的引數
  18. var param = request.PostDataByte;
  19. //其他HttpWebRequest引數基本都有
  20. };

示例

https://github.com/a935368322/Kogel.Net/blob/master/Kogel.Net.Test/Command/HttpClientCommand.cs

框架開源,完整框架原始碼可以去Github上下載:

https://github.com/a935368322/Kogel.Net

如有問題也可以加QQ群討論:

技術群 710217654