# 在dotnet framework MVC使用HttpClientFactory,post json,api爬蟲必備 ###### tags: `程式設計` `C#` HttpClientFactory 是在 .net core的元件,要在dotnet framework MVC環境下使用,有兩種方法,基本上都是透過 nuget 安裝元件 以下兩個二選一 1. 安裝 可以相依性插入的 Unity.Mvc 2. 安裝 Microsoft.Owin.Host.SystemWeb (會順便安裝OWIN) 隨後在安裝這兩個 * Microsoft.Extensions.DependencyInjection * Microsoft.Extensions.Http ## httpclient基礎範例程式碼 https://docs.microsoft.com/zh-tw/dotnet/api/system.net.http.httpclient?view=netcore-3.1 其中這兩個方法 (get post) 會是最常用的 * GetStringAsync(String) 將 GET 要求傳送至指定的 URI,並透過非同步作業,以字串形式傳回回應內容。 * PostAsync(String, HttpContent) 以非同步作業的方式,將 POST 要求傳送至指定的 URI。 其餘請參考保哥的影片 https://www.youtube.com/watch?v=TLRmL8CNUT4 或是下載保哥的範例程式碼 https://github.com/doggy8088/Mvc5HttpClientFactoryDemo 範例程式碼僅有 get ,如要使用 post 的程式碼如下 ```=C# public async Task<MyClass> Get() { HttpClient httpClient = _clientFactory.CreateClient(); //以下是走json的方式 var myClass = new MyClass() { Id = 123, Name = "Test" }; var stringContent = new StringContent(JsonConvert.SerializeObject(myClass), System.Text.Encoding.UTF8, "application/json"); var message = await httpClient.PostAsync("https://www.google.com.tw", stringContent); //以下是走表單的方式 var comment = "Hello"; var questionId = 1; var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("comment", comment), new KeyValuePair<string, string>("questionId", questionId) }); var message2 = await httpClient.PostAsync("https://www.google.com.tw", formContent); message.EnsureSuccessStatusCode(); var responseContent = await message.Content.ReadAsStringAsync(); var responseModel = JsonConvert.DeserializeObject<MyClass>(responseContent); return responseModel; } ``` ## 工具用網站 要建立測試 api 回傳 json可以利用這個網站 https://designer.mocky.io/ 要把json 轉回 C# 物件,可以利用這個網站 https://json2csharp.com/ ## HttpClientFactory 和 HttpClient 的比較 httpclient的缺點:如果每個連線開啟一個且用完就釋放,但 windows 預設還是要 wait 240秒才會真的釋放 如果預先註冊好共用同一個 httpclient,可以解決上面的wait問題 但是會衍伸新的問題 1. 不同請求有各自的專屬 header 想要共用就不行了,註冊的時候就綁死header 2. 如果dns有更換,要整個程式 restart 才能讓更換 httpclient 目標主機ip httpclientfactory就是解決這些問題用的 ## 參考資料 [Tools] 簡化使用HttpClient呼叫API的好工具 - Microsoft.AspNet.WebApi.Client、Flurl https://dotblogs.com.tw/Null/2020/04/14/213342 How to post data using HttpClient? https://stackoverflow.com/questions/20005355/how-to-post-data-using-httpclient HttpClientFactory 使用說明 及 對 HttpClient 的回顧和對比 https://www.itread01.com/content/1564990083.html
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.