顯示具有 HttpClient 標籤的文章。 顯示所有文章
顯示具有 HttpClient 標籤的文章。 顯示所有文章

2024年4月27日 星期六

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(二)verify

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(二)verify

2024-04-27、2024-05-16

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

因 RestSharp 於 2009 年首次推出,成為 .NET 開發者中非常受歡迎的一個選擇。在 RestSharp v107 開始,語法大改;而 .NET Framework 4.5 (2012 年推出) 開始提供 HttpClient,考慮改用這個。

********************************************************************************

Web.Config

<?xml version="1.0" encoding="utf-8"?>
<!--
  如需如何設定 ASP.NET 應用程式的詳細資訊,請前往
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <appSettings>
    <add key="IRESTfulServerUrl" value="https://網址/" />
    <add key="IRESTfulAccount" value="帳號" />
    <add key="IRESTfulPassword" value="密碼" />
  </appSettings>
</configuration>



********************************************************************************

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Http;	// NuGet 安裝,HttpClient 要使用
using System.Threading.Tasks;

namespace WebApplication1
{

    public class VerifyResult
    {
        public string message { get; set; }
        public string describe { get; set; }

        // RestSharp v106 要這樣才能運作
        //public List<VerifyData> data { get; set; }

        // RestSharp v107 開始或 HttpClient ,要這樣才能運作
        public VerifyData data { get; set; }
    }

    public class VerifyData
    {
        public string product_class { get; set; }
        public string product_account { get; set; }
        public string product_name { get; set; }
        public string contact_account { get; set; }
        public string contact_name { get; set; }
        public string contact_cellphone { get; set; }
        public string contact_mail { get; set; }
        public string contact_dept { get; set; }
        public string contact_tel { get; set; }
        public string contact_extend { get; set; }
        public string contact_title { get; set; }
        public string status { get; set; }
        public List<string> contact_category { get; set; }
    }
    public partial class Default : System.Web.UI.Page
    {
        protected async void Page_Load(object sender, EventArgs e)
        {
            string account = "略";
            string password = "略";


            VerifyResult content = new VerifyResult();
            content = await Verify_by_HttpClient("1", account, password);
        }

        #region === public async static VerifyResult Verify_by_HttpClient(string account_type, string account, string password) ===
        public async static Task<VerifyResult> Verify_by_HttpClient(string account_type, string account, string password)
        {
            string iRESTfulUrl = ConfigurationManager.AppSettings["IRESTfulUrl"];
            string iRESTfulSysId = ConfigurationManager.AppSettings["IRESTfulSysId"];
            string iRESTfulSysPass = ConfigurationManager.AppSettings["IRESTfulSysPass"];
			string acc = TextBox_Acc.Text.Trim();
			string pass = TextBox_Pass.Text.Trim();
			
            var httpClient = new HttpClient();
            try
            {
//----------------------------------------------------
// 2024-05-16 補,發現回傳的 VerifyResult,如果成功 (0001) 和不成功的格式不同,VerifyData 是 [],
// 不成功的 在 VerifyResult v = serializer.Deserialize<VerifyResult>(jsonTextReader); 會出錯
/*
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WebApplication1.Models.VerifyData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. 
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. 
JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path 'data', line 1, position 68.
*/
// 只好做一個符合格式的
// 此問題在以前用 RestSharp v106 不會有
#region === 1 ===

var requestBody2 = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("sysid", iRESTfulSysId), new KeyValuePair<string, string>("syspass", iRESTfulSysPass), new KeyValuePair<string, string>("acc", acc), new KeyValuePair<string, string>("pass", pass), });
var response2 = await httpClient.PostAsync(WS_URL + "restful/verify", requestBody2);
                bool isSuccessStatusCode2 = response2.IsSuccessStatusCode;
                HttpResponseMessage ensureSuccessStatusCode2 = new HttpResponseMessage();
                if (isSuccessStatusCode2 == false)
                {
                    ensureSuccessStatusCode2 = response2.EnsureSuccessStatusCode();
                }

                var responseStream2A = response2.Content.ReadAsStreamAsync().Result;
                using (var responseStream2B = await response2.Content.ReadAsStreamAsync())
                {
                    using (StreamReader streamReader2B = new StreamReader(responseStream2B))
                    using (Newtonsoft.Json.JsonTextReader jsonTextReader2B = new Newtonsoft.Json.JsonTextReader(streamReader2B))
                    {
                        var json = streamReader2B.ReadToEnd(); // 讀取 JSON 資料到字串中
                        var jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
                        string message = jsonObject.message;
                        
                        if (message !="0001")
                        {
                            VerifyResult vv = new VerifyResult();
                            vv.message = message;
                            return vv;
                        }
                    }
                }
                #endregion
//----------------------------------------------------
var requestBody = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("sysid", iRESTfulSysId),
                    new KeyValuePair<string, string>("syspass", iRESTfulSysPass),
                    new KeyValuePair<string, string>("acc", acc),
                    new KeyValuePair<string, string>("pass", pass),
                });                var response2 = await httpClient.PostAsync(WS_URL + "restful/verify", requestBody);

var response = await httpClient.PostAsync(iRESTfulUrl + "restful/verify", requestBody); bool isSuccessStatusCode = response.IsSuccessStatusCode; HttpResponseMessage ensureSuccessStatusCode = new HttpResponseMessage(); if (isSuccessStatusCode == false) { ensureSuccessStatusCode = response.EnsureSuccessStatusCode(); } var responseStream2 = response.Content.ReadAsStreamAsync().Result; using (var responseStream = await response.Content.ReadAsStreamAsync()) { using (StreamReader streamReader = new StreamReader(responseStream)) using (Newtonsoft.Json.JsonTextReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { //不可以同時 ReadToEnd 和 Deserialize,只能擇一使用 //var json = streamReader.ReadToEnd(); // 讀取 JSON 資料到字串中 var serializer = new Newtonsoft.Json.JsonSerializer(); //return serializer.Deserialize<VerifyResult>(jsonTextReader); VerifyResult v = serializer.Deserialize<VerifyResult>(jsonTextReader); return v; } } } catch (HttpRequestException ex) { string exMsg = ""; if (ex != null) exMsg = ex.Message.ToString(); throw; } } #endregion } }

Default.aspx

<%@ Page Async="true" Language="C#" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

...(略)

實際測試,在 Visual Studio 中 Debug,v確實有拿到回傳資料。

(完)

相關

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(二)verify
https://shaurong.blogspot.com/2024/04/aspnetwebform-restsharp-10615_27.html

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(一)
https://shaurong.blogspot.com/2024/04/aspnetwebform-restsharp-10615.html

[研究]ASP.NET,使用 HttpClient 時 using System.Net.Http; 編譯出錯:System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)
https://shaurong.blogspot.com/2024/04/aspnetsystemnet-http.html

RestSharp Next (v107) | RestSharp
https://restsharp.dev/v107/#restsharp-v107

NuGet Gallery | RestSharp
https://www.nuget.org/packages/RestSharp/

RestSharp - Simple .NET REST Client - GitHub
https://github.com/restsharp/RestSharp

[研究][ASP.NET WebForm C#]Newtonsoft.Json 13.0.1 序列化、反序列化測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cnewtonsoftjson-1301.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(二)
https://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web_26.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)
http://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web.html

[研究][ASP.NET WebForm C#]WebClient 呼叫 Web API、REST/RESTful API 測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cwebclient-web.html



2024年4月22日 星期一

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(一)getProductList

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(一)getProductList

2024-04-22

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

因 RestSharp 於 2009 年首次推出,成為 .NET 開發者中非常受歡迎的一個選擇。在 RestSharp v107 開始,語法大改;而 .NET Framework 4.5 (2012 年推出) 開始提供 HttpClient,考慮改用這個。

********************************************************************************

Web.Config

<?xml version="1.0" encoding="utf-8"?>
<!--
  如需如何設定 ASP.NET 應用程式的詳細資訊,請前往
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <appSettings>
    <add key="IRestfulServerUrl" value="https://網址/" />
    <add key="IRestfulAccount" value="帳號" />
    <add key="IRestfulPassword" value="密碼" />
  </appSettings>
</configuration>


Models\MyModel.cs

略


********************************************************************************

Default.aspx

using RestSharp;    // NuGet 安裝 RestSharp 106.15
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Http;    // HttpClient 使用
using System.Threading.Tasks;
using WebApplication1.Models;   // 自己寫的

namespace WebApplication1
{
    public class IRestfulClient
    {
        static readonly string IRestfuleServerURL = ConfigurationManager.AppSettings["IRestfulServerUrl"];
        static readonly string IRestfulAccount = ConfigurationManager.AppSettings["IRestfulAccount"];
        static readonly string IRestfulPassword = ConfigurationManager.AppSettings["IRestfulPassword"];

       ...(略)
public static ProductListResult getProductList() { var client = new RestClient(IRestfuleServerURL + "rest/getProductList"); var request = new RestRequest(Method.POST); RestResponse<ProductListResult> response2; request.AddParameter("acc", IRestfulAccount); request.AddParameter("pass", IRestfulPassword); try { response2 = (RestSharp.RestResponse<ProductListResult>)client.Execute<ProductListResult>(request); } catch (Exception) { throw; } return response2.Data; } public static async Task<ProductListResult> getProductList_by_HttpClient()
{ var httpClient = new HttpClient(); try { var requestBody = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("acc", IRestfulAccount), new KeyValuePair<string, string>("pass", IRestfulPassword) }); var response = await httpClient.PostAsync(IRestfuleServerURL + "rest/getProductList", requestBody);
bool isSuccessStatusCode = response.IsSuccessStatusCode; HttpResponseMessage ensureSuccessStatusCode = new HttpResponseMessage(); if (isSuccessStatusCode == false) { ensureSuccessStatusCode = response.EnsureSuccessStatusCode(); } using (var responseStream = await response.Content.ReadAsStreamAsync()) { using (var streamReader = new StreamReader(responseStream)) using (var jsonReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { var serializer = new Newtonsoft.Json.JsonSerializer(); return serializer.Deserialize<ProductListResult>(jsonReader); } } } catch (HttpRequestException) { throw; } } ...(略) } }

Default.aspx

<%@ Page Async="true" Language="C#" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="用 RestSharp v106 呼叫 Restful API" OnClick="Button1_Click" /><br />
        <asp:Button ID="Button2" runat="server" Text="用 HttpClient 呼叫 Restful API" OnClick="Button2_Click" /><br />
        <asp:Label ID="Label_MSG1" runat="server"></asp:Label><br />
    </form>
</body>
</html>


Default.aspx.cs

using System;
using System.Net.Http;  // 要用 NuGet 安裝
using WebApplication1.Models;   // IRestfulClient 使用的 Client

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        public static readonly HttpClient client = new HttpClient();
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Label_MSG1.Text = "";
            ProductListResult content = new ProductListResult();
            try
            {
                content = IRestfulClient.getProductList();
                Label_MSG1.ForeColor = System.Drawing.Color.Green;
                Label_MSG1.Text = DateTime.Now.ToString() + " RestSharp 106.15 執行成功。";
            }
            catch (Exception ex)
            {
                //throw;
                Label_MSG1.ForeColor = System.Drawing.Color.Red;
                if (ex != null)
                {
                    Label_MSG1.Text = ex.Message.ToString();
                }
                else
                {
                    Label_MSG1.Text = "不明錯誤。";
                }
            }
        }

        protected async void Button2_Click(object sender, EventArgs e)
        {
            Label_MSG1.Text = "";
            ProductListResult content = new ProductListResult();
            try
            {
                content = await IRestfulClient.getProductList_by_HttpClient();
                Label_MSG1.ForeColor = System.Drawing.Color.Green;
                Label_MSG1.Text = DateTime.Now.ToString() + " HttpClient 執行成功。";
            }
            catch (Exception ex)
            {
                //throw;
                Label_MSG1.ForeColor = System.Drawing.Color.Red;
                if (ex != null)
                {
                    Label_MSG1.Text = ex.Message.ToString();
                }
                else
                {
                    Label_MSG1.Text = "不明錯誤。";
                }
            }
        }
        //---
    }
}






(完)

相關

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫https://shaurong.blogspot.com/2024/04/aspnetwebform-restsharp-10615.html

[研究]ASP.NET,使用 HttpClient 時 using System.Net.Http; 編譯出錯:System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)
https://shaurong.blogspot.com/2024/04/aspnetsystemnet-http.html

RestSharp Next (v107) | RestSharp
https://restsharp.dev/v107/#restsharp-v107

NuGet Gallery | RestSharp
https://www.nuget.org/packages/RestSharp/

RestSharp - Simple .NET REST Client - GitHub
https://github.com/restsharp/RestSharp

[研究][ASP.NET WebForm C#]Newtonsoft.Json 13.0.1 序列化、反序列化測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cnewtonsoftjson-1301.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(二)
https://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web_26.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)
http://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web.html

[研究][ASP.NET WebForm C#]WebClient 呼叫 Web API、REST/RESTful API 測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cwebclient-web.html



[研究]ASP.NET,使用 HttpClient 時 using System.Net.Http; 編譯出錯:System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)

[研究]ASP.NET,使用 HttpClient 時 using System.Net.Http; 編譯出錯:System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)

2024-04-22

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

Visual Studio 2019 中編譯出錯


using System.Net.Http;   這一行編譯錯誤
 error CS0234: 命名空間 'System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)

********************************************************************************

解決:

NuGet 安裝 System.Net.Http 套件。


WebApplication1

正在安裝:

  • System.IO.4.3.0
  • System.Runtime.4.3.0
  • System.Security.Cryptography.Encoding.4.3.0
  • System.Security.Cryptography.Primitives.4.3.0
  • System.Security.Cryptography.Algorithms.4.3.0
  • System.Security.Cryptography.X509Certificates.4.3.0
  • System.Net.Http.4.3.4

********************************************************************************

User

 HttpClient 從 .NET Framework 哪一版開始提供 ?

ChatGPT

HttpClient 類型最初是在 .NET Framework 4.5 中引入的。在這個版本中,它被添加到 System.Net.Http 命名空間中,並且是一個輕量級的 HTTP 客戶端,用於發送 HTTP 請求並處理響應。在後續的 .NET Framework 版本中,它已經得到了改進和擴展。

********************************************************************************

User

 .NET Framework 4.5  何時開始提供

ChatGPT

.NET Framework 4.5 於 2012 年 8 月 15 日正式發布。這個版本引入了許多新功能和改進,包括 HttpClient 類型,這是一個用於發送 HTTP 請求的新型輕量級客戶端。

********************************************************************************

User

using System.Net.Http;   編譯錯誤 error CS0234: 命名空間 'System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)

ChatGPT

看來您在 .NET Framework 的環境中遇到了這個錯誤。在 .NET Framework 4.5 中,HttpClient 位於 System.Net.Http 命名空間中,但有時在使用上可能會遇到這種問題。

這種情況通常是因為專案中沒有正確引用所需的組件。您需要確保專案中包含了正確的組件引用,以便能夠使用 System.Net.Http 命名空間中的類型。

解決方法可能是確保您的專案已經引用了 System.Net.Http 組件。您可以通過以下步驟進行檢查:

  • 在 Visual Studio 中,右鍵點擊專案,然後選擇 "管理 NuGet 程式包"。
  • 在 "已安裝" 選項卡中檢查是否已安裝了 System.Net.Http 程式包。如果沒有,請在 "線上" 選項卡中搜索並安裝。
  • 如果您不使用 NuGet,請確保專案的引用中包含了 System.Net.Http 組件。您可以在專案的屬性中的 "參考" 部分進行檢查和添加。

如果您確認了以上步驟但仍然遇到問題,請確保您的開發環境中已正確安裝了 .NET Framework 4.5 或更新版本。

********************************************************************************

User

System.Net.Http 是 Microsoft 提供的套件 ?

ChatGPT

是的,System.Net.Http 是由 Microsoft 提供的 .NET 標準庫中的一個套件。它包含了 HttpClient 類型,這是用於發送 HTTP 請求的核心類型之一。HttpClient 提供了一個簡潔且功能豐富的 API,可以用於發送 HTTP 請求並處理響應。這個套件是 .NET Framework 和 .NET Core 的一部分,所以它可以在這些平台上使用。

********************************************************************************

User

既然是 .NET Framework 提供,為何還要用 NuGet 安裝 ?

ChatGPT

您提出了一個很好的問題。在某些情況下,特別是在較早的 .NET Framework 版本中,System.Net.Http 套件可能需要通過 NuGet 來安裝,而不是作為 .NET Framework 的一部分提供。

主要的原因之一是.NET Framework 4.5 的發布時機較早,而 NuGet 作為一個套件管理工具,可以用來補充 .NET Framework 的功能。這使得 Microsoft 可以更靈活地引入和更新庫,並讓開發人員能夠在專案中使用最新的版本。

此外,即使在後續版本的 .NET Framework 中,有時開發人員也可能選擇通過 NuGet 安裝 System.Net.Http 套件,這樣可以更容易地管理依賴關係和版本。另外,NuGet 還提供了更頻繁的更新和改進,這樣開發人員就可以更快地獲得最新的功能和修復程序。

總的來說,使用 NuGet 安裝 System.Net.Http 套件的方式可以讓開發人員更靈活地管理和更新庫,並確保他們可以使用最新的功能和修復程序。

********************************************************************************


(完)

相關

[研究]ASP.NET,WebForm,HttpClient client = HttpClientFactory.Create(); 與 HttpClient client = HttpClient.Create(); 差別優缺點

[研究]ASP.NET,WebForm,HttpClient client = HttpClientFactory.Create(); 與 HttpClient client = HttpClient.Create(); 差別優缺點

2024-04-22

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

請問兩者差別?優點?缺點?

HttpClient client = HttpClientFactory.Create();

HttpClient client = HttpClient.Create();

ChatGPT

這兩種方法的差別在於 HttpClient 的建立方式不同。

HttpClientFactory.Create() 使用的是 .NET Core 中的 IHttpClientFactory,可以用來創建和管理 HttpClient 的實例,提供了一個更好的方式來處理 HttpClient 的生命週期管理、資源共享和緩存。

而 HttpClient.Create() 則是直接使用 HttpClient 的建構子建立新的 HttpClient 實例,每次調用都會創建一個新的 HttpClient 實例,並且該實例不會被重複使用。

使用 IHttpClientFactory 的優點:

  • 管理 HttpClient 的生命週期,減少連接數量和資源消耗。
  • 可以使用 HttpClient 的 Named Client 功能,方便配置和使用。
  • 可以配置 HttpClient 的行為,例如 Timeout、Headers、BaseAddress 等等。
  • 可以支援緩存和重試機制,提高可靠性。
  • 可以減少 HttpClient 實例的設定代碼,簡化開發。

使用 HttpClient.Create() 的優點:

  • 簡單易用,不需要透過 DI 等其他機制取得 HttpClient 的實例。
  • 可以快速建立一個新的 HttpClient 實例,適用於只需要臨時使用 HttpClient 的場景。

使用 IHttpClientFactory 的缺點:

  • 需要透過 DI 機制來取得 HttpClient 的實例,開發者需要理解 DI 的使用方法。
  • 需要額外進行配置和設定,比直接使用 HttpClient 的建構子複雜。
  • 需要額外的額外套件支援,例如 Microsoft.Extensions.Http。

使用 HttpClient.Create() 的缺點:

  • 每次使用都需要建立一個新的 HttpClient 實例,會導致資源浪費和效能問題。
  • 無法進行 HttpClient 的生命週期管理,容易造成連接數量過多和資源消耗。
  • 無法使用 HttpClient 的 Named Client 功能,需要額外的代碼來進行配置和管理。

總之,使用 IHttpClientFactory 可以提供更好的 HttpClient 管理方式,適用於大多數情況。只有在一些簡單的臨時場景下,使用 HttpClient.Create() 才是比較好的選擇。

********************************************************************************

WebForm, 而非 .NET Core,請問下面兩者差別?優點?缺點?

HttpClient client = HttpClientFactory.Create();

HttpClient client = HttpClient.Create();

ChatGPT

在 WebForm 中,沒有提供 HttpClientFactory 這個工具,所以這兩個方法都不能在 WebForm 中使用。

在 .NET Framework 中,可以使用 HttpClient 的建構子直接創建新的 HttpClient 實例,例如 HttpClient client = new HttpClient()。使用這種方式創建 HttpClient 實例的優點是簡單易用,不需要額外的套件或設定。

但是,使用這種方式創建 HttpClient 實例的缺點是每次調用都會創建一個新的 HttpClient 實例,會導致資源浪費和效能問題,特別是當應用程式需要與多個 Web API 進行通訊時。此外,使用這種方式,也無法進行 HttpClient 的生命週期管理,容易造成連接數量過多和資源消耗。

綜上所述,在 WebForm 中,建議使用 HttpClient 的建構子直接創建新的 HttpClient 實例,但要注意避免創建過多實例和浪費資源。如果需要進行 HttpClient 的生命週期管理和資源共享,可以使用自行實現的管理機制,例如使用 Singleton 設計模式來管理 HttpClient 實例。

********************************************************************************

下面網頁就在 WebForm 使用 HttpClientFactory

https://shaurong.blogspot.com/2023/03/aspnet-httpclientfactory-restful-api.html

ChatGPT

非常抱歉,我理解錯誤了。在 WebForm 中,實際上可以使用 HttpClientFactory 套件,以便在使用 HttpClient 時進行生命週期管理和資源共享。這是一個優點,可以幫助減少資源浪費和提高效能。另外,使用 HttpClientFactory 還可以更方便地進行配置和設定,例如在 Startup 類別中進行設定。

相比之下,直接使用 HttpClient 的建構子來創建 HttpClient 實例的缺點,包括每次調用都會創建新的 HttpClient 實例,容易導致資源浪費和效能問題,以及無法進行生命週期管理和資源共享的缺點。

********************************************************************************

(完)

2024年4月19日 星期五

[研究]ASP.NET,比較表,常用 Restful API Client 套件Flurl.Http, Refit, RestEase, RestSharp, HttpClient , HttpWebRequest 和 HttpWebResponse, HttpClientFactory,WebClient

[研究]ASP.NET,比較表,常用 Restful API Client 套件Flurl.Http, Refit, RestEase, RestSharp, HttpClient , HttpWebRequest 和 HttpWebResponse, HttpClientFactory,WebClient 

2024-04-19

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

ASP.NET,WebForm,請比較下面 NuGet 提供的 Restful API Client 套件功能差異?優點?缺點?問世時間?是否 .NET Framework 內建提供?支援 .NET Framework 版本?推薦順序?用比較表

  • Flurl.Http
  • Refit
  • RestEase
  • RestSharp
  • HttpClient 
  • HttpWebRequest 和 HttpWebResponse 
  • HttpClientFactory 
  • WebClient 

ChatGPT
套件功能優點缺點問世時間.NET Framework 內建提供支援 .NET Framework 版本推薦順序
Flurl.Http提供流暢的API呼叫,易於閱讀和維護簡潔的API設計、輕量級且易於使用、具有優秀的擴展性對於大型專案,可能缺乏一些進階功能2014年3月發佈否.NET Framework 4.5及以上4
Refit使用C#界面定義API,易於使用使用熟悉的C#界面定義API、自動序列化和反序列化、具有輕量級和簡潔的語法部分進階功能可能不支持,需手動實現2015年2月發佈否.NET Framework 4.5及以上3
RestEase使用C#界面定義API,支援多種語法支援C#界面定義API、提供多種語法支援、具有自動序列化和反序列化文件和社區支援較少、部分進階功能可能不支持,需手動實現2016年6月發佈否.NET Framework 4.5及以上5
RestSharp經典的.NET Restful API客戶端廣泛使用,穩定可靠、支援多種序列化方式、具有較為完善的功能由於歷史悠久,可能缺乏一些現代化的特性、部分進階功能需要額外擴展2009年2月發佈否.NET Framework 4.0及以上1
HttpClient.NET內建的HTTP客戶端.NET內建,無需額外安裝、支援非同步操作、支援多種認證方式API設計較為冗長,不夠簡潔、需要手動處理許多細節,使用起來相對複雜2012年8月發佈是.NET Framework 4.5及以上2
HttpWebRequest 和 HttpWebResponse.NET內建的HTTP請求和回應.NET內建,無需額外安裝、適用於特定情境下的低階控制使用起來相對複雜、需要手動處理許多細節-是.NET Framework 1.1及以上6
HttpClientFactory.NET Core/.NET 5+的HTTP客戶端工廠提供HTTP客戶端實例的管理和重用、具有配置和擴展性需要理解並配置工廠以使用、對於小型項目,可能帶來額外的複雜性2018年9月發佈是.NET Core/.NET 5+7
WebClient.NET內建的HTTP客戶端.NET內建,無需額外安裝、支援同步和非同步操作、較HttpClient簡潔,對於一些基本的HTTP操作足夠使用功能相對較少,不適用於較複雜的場景-是.NET Framework 2.0及以上8

推薦順序根據功能、易用性、社區支持以及最新版本狀況給出,但最終選擇應根據具體項目需求而定。

註:推薦順序,敝人問了幾次,回答不盡相同。敝人沒查證資料正確與否。

********************************************************************************
問世時間順序?愈早排愈上方

ChatGPT

以下是這些 Restful API Client 套件的問世時間順序:
  1. HttpWebRequest 和 HttpWebResponse (.NET Framework 1.1內建:2003年4月)
  2. WebClient (.NET Framework 2.0內建:2005年11月)
  3. RestSharp (2009年2月)
  4. HttpClient (.NET Framework 4.5內建,2012年8月)
  5. Flurl.Http (2014年3月)
  6. Refit (2015年2月)
  7. RestEase (2016年6月)
  8. HttpClientFactory (.NET Core 2.1內建,2018年5月)
這些套件依據它們的問世時間由早至晚排列。

(完)

相關

[研究]ASP.NET,比較表,常用 Restful API Client 套件Flurl.Http, Refit, RestEase, RestSharp, HttpClient , HttpWebRequest 和 HttpWebResponse, HttpClientFactory,WebClient 
https://shaurong.blogspot.com/2024/04/aspnet-restful-api-client-flurlhttp.html

[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫(三)反序列化
https://shaurong.blogspot.com/2023/03/aspnet-restsharp-v107-restful-api_85.html

[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫(二)模組化
https://shaurong.blogspot.com/2023/03/aspnet-restsharp-v107-restful-api_27.html

[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫(一)成功
https://shaurong.blogspot.com/2023/03/aspnet-restsharp-v107-restful-api.html

[研究][ASP.NET]用 HttpClientFactory 做 RESTful API 呼叫(三)反序列化
https://shaurong.blogspot.com/2023/03/aspnet-httpclientfactory-restful-api_2.html

[研究][ASP.NET]用 HttpClientFactory 做 RESTful API 呼叫(二)模組化
https://shaurong.blogspot.com/2023/03/aspnet-httpclientfactory-restful-api_27.html

[研究][ASP.NET]用 HttpClientFactory 做 RESTful API 呼叫(一)成功
https://shaurong.blogspot.com/2023/03/aspnet-httpclientfactory-restful-api.html

[研究]ASP.NET RESTful API: 比較 HTTPClient , RestSharp , WebClient, HttpClientFactory, Flurl, Refit, RestEase
https://shaurong.blogspot.com/2023/03/aspnet-restful-api-httpclient-restsharp.html

[研究][ASP.NET]RestSharp 106 升級 v107疑難排解:未包含 HasValue 的定義
https://shaurong.blogspot.com/2023/03/aspnetrestsharp-106-v107-hasvalue.html

[研究][ASP.NET]用 HttpClient 做 RESTful API 呼叫
https://shaurong.blogspot.com/2023/03/aspnet-httpclient-restful-api.html

[研究][ASP.NET]ChatGPT,請提供完整 RestSharp v107 範例程式https://shaurong.blogspot.com/2023/03/aspnetchatgpt-restsharp-v107.html

2023年3月2日 星期四

[研究][ASP.NET]用 HttpClient 做 RESTful API 呼叫

[研究][ASP.NET]用 HttpClient 做 RESTful API 呼叫

2023-03-02

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C#

HttpClient 類別 (System.Net.Http) | Microsoft Learn
https://learn.microsoft.com/zh-tw/dotnet/api/system.net.http.httpclient?view=netframework-4.8

********************************************************************************

Default.aspx

<%@ Page Language="C#" Async="true" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
            <asp:Label ID="Label1" runat="server"></asp:Label>
        </div>
    </form>
</body>
</html>


注意,Page 要多加上 Async="true",否則會有下面錯誤

非同步作業目前無法開始。非同步作業只有在非同步處理常式或模組或是頁面生命週期中特定事件期間中才能開始。如果執行頁面時發生此例外狀況,請確認頁面已標示為 <%@ Page Async="true" %>。此例外狀況也可能表示嘗試呼叫一般在 ASP.NET 要求處理中不支援的 "async void" 方法。相反地,非同步方法應傳回工作而呼叫端應等候它。

********************************************************************************

Default.aspx.cs

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication6
{
    public class GetObjectResult
    {
        public string message { get; set; }
        public string describe { get; set; }
        public List<GetObjectData> data { get; set; }
    }

    public class GetObjectData
    {
        public string product_class { get; set; }
        public string product_name { get; set; }
        public string product_status { get; set; }
        public string product_attri { get; set; }
        public string product_level { get; set; }
        public string product_type { get; set; }
    }
	
    public partial class Default : System.Web.UI.Page
    {
        protected async void Page_Load(object sender, EventArgs e)
        {

        }

        protected async void Button1_Click(object sender, EventArgs e)
        {
            // 建立 HttpClient 實例
            HttpClient client = new HttpClient();

            try
            {
                // 呼叫 API 的 URL
                string url = "https://XXX.XXX.XXX/getObjectList";

                // 建立要傳送的資料
                var data = new Dictionary<string, string>
                {
                    { "code", "帳號" },
                    { "pass", "密碼" }
                };

                // 建立要傳送的內容
                var content = new FormUrlEncodedContent(data);

                // 呼叫 API,取得回應
                HttpResponseMessage response = await client.PostAsync(url, content);

                // 檢查回應是否成功
                if (response.IsSuccessStatusCode)
                {
                    // 取得回應內容
                    string responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<GetObjectResult>(responseContent);

                    // 在頁面上顯示回應內容
                    //Response.Write(responseContent);  //OK

                    Response.Write(result.message);
                    Response.Write(result.describe);
                    foreach( var dd in result.data)
                    {
                        Response.Write(dd.product_name +"," + dd.product_level + "<br />");
                    }
                }
                else
                {
                    // 在頁面上顯示錯誤訊息
                    Response.Write("Error: " + response.StatusCode);
                }
            }
            catch (Exception ex)
            {
                // 在頁面上顯示錯誤訊息
                Response.Write("Error: " + ex.Message);
            }
        }
    }
}

這是一個實際測試過,真實可用的 Code,只是帳號、密碼、資料、網址做了些變更。

(完)

相關

[研究][ASP.NET]用 HttpClientFactory 做 RESTful API 呼叫
https://shaurong.blogspot.com/2023/03/aspnet-httpclientfactory-restful-api.html

[研究]ASP.NET RESTful API: 比較 HTTPClient , RestSharp , WebClient, HttpClientFactory, Flurl, Refit, RestEase
https://shaurong.blogspot.com/2023/03/aspnet-restful-api-httpclient-restsharp.html

[研究][ASP.NET]RestSharp 106 升級 v107疑難排解:未包含 HasValue 的定義
https://shaurong.blogspot.com/2023/03/aspnetrestsharp-106-v107-hasvalue.html

[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫
https://shaurong.blogspot.com/2023/03/aspnet-restsharp-v107-restful-api.html

[研究][ASP.NET]用 HttpClient 做 RESTful API 呼叫
https://shaurong.blogspot.com/2023/03/aspnet-httpclient-restful-api.html

[研究][ASP.NET]ChatGPT,請提供完整 RestSharp v107 範例程式https://shaurong.blogspot.com/2023/03/aspnetchatgpt-restsharp-v107.html


2022年2月26日 星期六

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API、JSON字串轉JSON Objection 測試(二)

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API、JSON字串轉JSON Objection 測試(二)

2022-02-26

續這篇

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)
http://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web.html

後來發現

HttpClient 類別
https://docs.microsoft.com/zh-tw/dotnet/api/system.net.http.httpclient?view=net-6.0&WT.mc_id=DOP-MVP-37580&viewFallbackFrom=netframework-4
HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
HttpClient 應該只建立一份並重複利用。為每次請求建立新的 HttpClient,重度使用下可能用光 Socket Port 導致 SocketException。以下是正確的寫法:

Visual Studio2022 v17.1.0 + ASP.NET + C# + Web Application + WebForm

Default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            
        </div>
    </form>
    <asp:Label ID="Label_MSG1" runat="server" Text="Label"></asp:Label>
</body>
</html>

Default.aspx.cs


using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        public static readonly HttpClient client = new HttpClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            _ = CallWebAPI();
        }
        protected Task CallWebAPI()
        {
            string account = "帳號";
            string password = "密碼";
            var values = new[]
            {
                new KeyValuePair<string, string>("account", account),
                new KeyValuePair<string, string>("pass", password)
            };
            try
            {
                using (FormUrlEncodedContent multipartFormDataContent =
                    new FormUrlEncodedContent(values))
                {
                    //HttpResponseMessage response =
                    //    await client.PostAsync("https://網址/rest/verify", 
                    //        multipartFormDataContent);
                    //response.EnsureSuccessStatusCode();
                    //string responseBody = await response.Content.ReadAsStringAsync();
                    //string responseBody = await response.Content.ReadAsStringAsync();
                    //Label_MSG1.Text = responseBody;

                    var requestUri = "https://網址/rest/verify";
var json = client.PostAsync(requestUri, multipartFormDataContent).Result.Content.ReadAsStringAsync().Result; JObject jo = Newtonsoft.Json.Linq.JObject.Parse(json); string message = jo["message"].ToString(); string data = jo["data"].ToString(); string contact_account = jo["data"]["contact_account"].ToString(); Label_MSG1.Text = json;
// Above three lines can be replaced with new helper method below // string responseBody = await client.GetStringAsync(uri); } } catch (HttpRequestException ex) { Label_MSG1.Text = "不明錯誤。"; if (ex != null) Label_MSG1.Text = ex.Message.ToString(); } return Task.CompletedTask; } } }


(完)

相關

RestSharp Next (v107) | RestSharp
https://restsharp.dev/v107/#restsharp-v107

NuGet Gallery | RestSharp
https://www.nuget.org/packages/RestSharp/

RestSharp - Simple .NET REST Client - GitHub
https://github.com/restsharp/RestSharp

[研究][ASP.NET WebForm C#]Newtonsoft.Json 13.0.1 序列化、反序列化測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cnewtonsoftjson-1301.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(二)
https://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web_26.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)
http://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web.html

[研究][ASP.NET WebForm C#]WebClient 呼叫 Web API、REST/RESTful API 測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cwebclient-web.html


[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)

2022-02-26

續這篇

[研究][ASP.NET WebForm C#]WebClient 呼叫 Web API、REST/RESTful API 測試
https://shaurong.blogspot.com/2022/02/aspnet-webform-cwebclient-web.html

Visual Studio2022 v17.1.0 + ASP.NET + C# + Web Application + WebForm

Default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        </div>
    </form>
    <asp:Label ID="Label_MSG1" runat="server" Text="Label"></asp:Label>
</body>
</html>

Default.aspx.cs


using System;
using System.Collections.Generic;
using System.Net.Http;

namespace WebApplication2
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            // WebRequest、WebClient 和 >servicepoint 已淘汰
            // https://docs.microsoft.com/zh-tw/dotnet/core/compatibility/networking/6.0/webrequest-deprecated
            // 請改用 System.Net.Http.HttpClient 類別。

            MultipartFormDataContent content = new MultipartFormDataContent();
            using (HttpClient client = new HttpClient())
            {
                //client.DefaultRequestHeaders.Add("");
                string account = "帳號";
                string password = "密碼";
                var values = new[]
                {
                    new KeyValuePair<string, string>("account", account),
                    new KeyValuePair<string, string>("pass", password)
                };
                using (FormUrlEncodedContent multipartFormDataContent = new FormUrlEncodedContent(values))
                {
                    var requestUri = "https://網址/rest/verify";
                    var json = client.PostAsync(requestUri, multipartFormDataContent).Result.Content.ReadAsStringAsync().Result;
                    Label_MSG1.Text = json;
					
		    //VerifyResult vResult = JsonConvert.DeserializeObject<VerifyResult>(json);
					
		    //JavaScriptSerializer js = new JavaScriptSerializer();
                    //VerifyResult info = js.Deserialize<VerifyResult>(html);
                }
            }
        }
    }
}

後來發現

HttpClient 類別
https://docs.microsoft.com/zh-tw/dotnet/api/system.net.http.httpclient?view=net-6.0&WT.mc_id=DOP-MVP-37580&viewFallbackFrom=netframework-4
HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
HttpClient 應該只建立一份並重複利用。為每次請求建立新的 HttpClient,重度使用下可能用光 Socket Port 導致 SocketException。以下是正確的寫法:

(完)

相關

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(二)
https://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web_26.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)
http://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web.html

[研究][ASP.NET WebForm C#]WebClient 呼叫 Web API、REST/RESTful API 測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cwebclient-web.html