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

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

或者使用Nuget命令新增包

Install-Package Kogel.Net

(一)註冊

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

//註冊HttpClient
services.AddKogelHttpClient();

其他環境直接

//請求操作
IHttpClient httpClient = new HttpClient(); //檔案訪問操作
IFileClient fileClient = new FileClient();

(二)使用

get請求

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

post請求

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

指定型別返回

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

自定義請求

//引數
var jsonData = JsonConvert.SerializeObject(new { cost_code = "837" });
var byteArr = Encoding.UTF8.GetBytes(jsonData); //請求頭
WebHeaderCollection header = new WebHeaderCollection();
header.Add("Authorization", $"Bearer {accessToken}"); //開始請求
var response = httpClient.Request(new KogelRequest
{
Method = "post",
Url = "https://localhost:44370/api/basic/cost_info/get_list",
ContentType = "application/json",
PostDataType = PostDataType.Byte,
PostDataByte = byteArr,
Header = header
});
Console.WriteLine(response.Result);

(三)檔案操作

通過IFileClient操作,和IHttpClient同理

檔案下載

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

檔案上傳

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

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

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

//aop監聽請求(只會作用於當前上下文)
//執行前
HttpBase.Aop.OnExecuting += (KogelRequest request) =>
{
//請求的url
var url = request.Url;
//請求的引數
var param = request.PostDataByte;
//其他HttpWebRequest引數基本都有
}; //執行後
HttpBase.Aop.OnExecuted += (KogelRequest request) =>
{
//請求的url
var url = request.Url;
//請求的引數
var param = request.PostDataByte;
//其他HttpWebRequest引數基本都有
};

示例

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

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

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

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

技術群 710217654