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

2024年4月29日 星期一

[研究][ASP.NET]RestSharp 106.15相依套件測試

[研究][ASP.NET]RestSharp 106.15相依套件測試

2023-04-29

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

最近一次更新元件,發現 RestSharp 相依套件數量似乎很多,建立一個新的、空的方案測試看看,考慮是否換掉它,改用微軟提供的 HTTPClient,或微軟更新提供的 HttpClientFactory   (Microsoft 已經棄用WebClient)。

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

WebApplication1

正在安裝:

RestSharp.106.15.0

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

(完)

相關

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 升級 RestSharp 110.2.0 做 Restful API 呼叫

[研究]ASP.NET,WebForm,將 RestSharp 106.15 升級 RestSharp 110.2.0 做 Restful API 呼叫

[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫(四)將 RestSharp 106.15 升級 RestSharp 110.2.0 

2024-04-22

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

因 RestSharp 在 v107 開始,語法大改。而且 v107 至 110.2.0,疑似陸續有改,之前研究測試的 Code 部分不能用。

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

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"];

       ...(略)
/* 註解,v106 和 v107 無法共存 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);
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; } } public static async Task<ProductListResult> getProductList_by_RestSharp107() { // 以 Postman 測試時,參數是加在 Body 才行, // 但在本程式用 AddBody 收不到參數,要用 AddParamter 才行 var client = new RestClient(IRestfuleServerURL + "rest/getProductList"); //var request = new RestRequest(Method.POST); //RestResponse<ProductListResult> response; var request = new RestRequest() .AddHeader("Content-Type", "application/x-www-form-urlencoded") .AddParameter("code", IRestfulAccount) .AddParameter("sys_pass", IRestfulPassword); try { //response2 = (RestSharp.RestResponse<ProductListResult>)client.Execute<ProductListResult>(request); var response = await client.PostAsync<ProductListResult>(request); var json = Newtonsoft.Json.JsonConvert.SerializeObject(response); //ProductListResult responseUnitListResultJson = Newtonsoft.Json.JsonConvert.DeserializeObject<ProductListResult>(responseVerifyResultString); //var responseVerifyResultString = await response.data.ReadAsStringAsync(); ProductListResult responseUnitListResultJson = Newtonsoft.Json.JsonConvert.DeserializeObject<ProductListResult>(json); //var responseMessage = response.message; //var responseData = response.data; //var responseDataJson = Newtonsoft.Json.JsonConvert.SerializeObject(responseData); //ProductListData productListData = Newtonsoft.Json.JsonConvert.DeserializeObject <ProductListData>(responseDataJson);//Error return responseUnitListResultJson;
//if (response.IsSuccessStatusCode) //{ // var responseVerifyResultString = await response.Content.ReadAsStringAsync(); // ProductListResult responseProductListResultJson = Newtonsoft.Json.JsonConvert.DeserializeObject<ProductListResult>(responseVerifyResultString); // return responseProductListResultJson; //} //else //{ // return null; //} /* // 發送請求並取得回應 //---------------------------------------- RestResponse response0 = client.Execute(request); //Response.Write(response0.Content+ "<br /><br />"); //成功 //var json0 = JsonConvert.SerializeObject(response0); //Response.Write("Json0: " +json0+"<br /><br />"); // Fail Message //---------------------------------------- var response1 = await client.PostAsync<ProductListResult>(request); //Response.Write(response.message); var json1 = Newtonsoft.Json.JsonConvert.SerializeObject(response); //Response.Write("Json : " + json+ "<br /><br />"); // 成功 //---------------------------------------- var response2 = await client.ExecuteAsync<ProductListResult>(request); //Response.Write("response2.Data.message : " + response2.Data.message+ "<br /><br />"); // 成功 //---------------------------------------- var response3 = await client.ExecutePostAsync<ProductListResult>(request); //Response.Write(response.message); var json3 = Newtonsoft.Json.JsonConvert.SerializeObject(response3); //Response.Write("Json3 : " + json3+ "<br /><br />"); // 成功 //---------------------------------------- var response4 = await client.PostAsync(request); //Response.Write(response.message); var json4 = Newtonsoft.Json.JsonConvert.SerializeObject(response4); //Response.Write("Json4 : " + json4+ "<br /><br />"); // 成功,但額外多一些怪資訊,因為沒有 Object 的 class //---------------------------------------- var response5 = await client.PostAsync<GetObjectResult>(request); //Response.Write(response.message); var json5 = Newtonsoft.Json.JsonConvert.SerializeObject(response5); //Response.Write("Json5 : " + json5 + "<br /><br />"); // 成功 //---------------------------------------- */ } catch (Exception) { throw; } //return response2.Data;
} ...(略) } }

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:Button ID="Button3" runat="server" Text="用 RestSharp 110.2.0 呼叫 Restful API" OnClick="Button3_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)
        {

        }

        /* RestSharp 106 和 RestSharp v107 無法共存
        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 = "不明錯誤。";
                }
            }
        }

        // RestSharp v107 開始寫法大改
        protected async void Button3_Click(object sender, EventArgs e)
        {
            Label_MSG1.Text = "";
            ProductListResult content = new ProductListResult();
            try
            {
                content = await IRestfulClient.getProductList_by_RestSharp107();
                Label_MSG1.ForeColor = System.Drawing.Color.Green;
                Label_MSG1.Text = DateTime.Now.ToString() + " RestSharp 110.2.0 執行成功。";
            }
            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 改用 RestSharp 110.2.0 做 Restful API 呼叫
[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫(四)將 RestSharp 106.15 升級 RestSharp 110.2.0
https://shaurong.blogspot.com/2024/04/aspnetwebform-restsharp-10615-restsharp.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




[研究]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



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月27日 星期一

[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫(三)反序列化

[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫(三)反序列化

2023-03-27

續這篇

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

也是類似的情況,某些結構的 class 不能用;怎麼換都有問題

//public List<string> contact_category { get; set; } // RestSharp v106 可用,v107 不行

//public string[] contact_category { get; set; }

//public List<string> contact_category { get; set; }

//public String[] contact_category { get; set; }

//public string contact_category { get; set; }

//public List<VerifyCategory> contact_category { get; set; }

訊息不太相同,而是

The JSON value could not be converted to System.Collections.Generic.List

如果能改 Server 端,不要用 List<string>,改用 string 應可解。如果只能改呼叫端,暫時

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

2023-03-27補:解決了,和相關人員對照 Server 端的 CODE 後,Client 端

public List<VerifyData> data { get; set; }

改成

public VerifyData data { get; set; }

其實 RestSharp 106 不該讓上面通過,它是錯誤的;結果到了 RestSharp v107 才判斷出它是錯的。

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

2023-03-30補:某系統先改了class,結果不能用,改回正常;不管合不合理,或是 RestSharp的舊版有 Bug?或不是?或是某些因素。

RestSharp v106 必須用 public List<VerifyData> data { get; set; },否則回傳會 null;

RestSharp v107 必須用 public VerifyData data { get; set; }

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

(完)

相關

[研究][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

[研究][ASP.NET]用 HttpClientFactory 做 RESTful API 呼叫(三)反序列化

[研究][ASP.NET]用 HttpClientFactory 做 RESTful API 呼叫(三)反序列化

2023-03-27

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

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

在某個 RESTful API 呼叫時候,JsonConvert.SerializeObject 反序列化會出現

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WebApplication1.Models.Contact]' 

    because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Path 'data.product_class', line 1, position 60.

無法將當前 JSON 對象(例如 {"name":"value"})反序列化為類型 'System.Collections.Generic.List`1[WebApplication1.Models.VerifyData]',因為該類型需要一個 JSON 陣列(例如 [1, 2,3]) 正確反序列化。

要修復此錯誤,請將 JSON 更改為 JSON 陣列(例如 [1,2,3])或更改反序列化類型,使其成為普通的 .NET 類型(例如,不是像整數這樣的原始類型,也不是像這樣的集合類型 可以從 JSON 對象反序列化的陣列或 List<T>)。 JsonObjectAttribute 也可以添加到類型以強制它從 JSON 對象反序列化。

路徑“data.product_class”,第 1 行,位置 60。

簡單的說 JsonConvert.SerializeObject認為 resultString2 不是一個有效的 JSON 陣列。

但此狀況在使用 RestSharp v106 (內含反序列化能力) 並沒有發生;表示 RestSharp v106 的反序列化能力或寬容度勝過 Newtonsoft.Json 套件。

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

下面結構正常

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class MyModel
    {
    }
	public class ProductListResult
    {
        public string message { get; set; }
        public string describe { get; set; }
        public List<ProductListData> data { get; set; }
    }

    public class ProductListData
    {
	public string product_oid { get; set; }
        public string product_name { get; set; }
        public string product_level { get; set; }
        public string product_official_type { get; set; }
        public string product_type { get; set; }
        public string product_sub_type { get; set; }
        public string product_adjust_note { get; set; }
    }
}

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

這個結構異常

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class MyModel
    {
    }

     public class VerifyResult
    {
        public string message { get; set; }
        public string describe { get; set; }
        public List<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 status { get; set; }
        public List<string> contact_category { get; set; }
    }
}

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

string 的第一個字改大寫成 String,也是不行。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class MyModel
    {
    }

     public class VerifyResult
    {
        public string message { get; set; }
        public string describe { get; set; }
        public List<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 status { get; set; }
        public List<String> contact_category { get; set; }
    }
}

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

改成下面,測試失敗。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class MyModel
    {
    }

     public class VerifyResult
     {
        public string message { get; set; }
        public string describe { get; set; }
        public List<VerifyData> data { get; set; }
     }

	public class VerifyCategory
	{
		public string category_name { 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 status { get; set; }
		public List<VerifyCategory> contact_category { get; set; }
	}
}

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

改成下面,測試失敗。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class MyModel
    {
    }

     public class VerifyResult
    {
        public string message { get; set; }
        public string describe { get; set; }
        public List<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 status { get; set; }
        public string contact_category { get; set; }
    }
}

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

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

因為 Server 端不是敝人負責,碰到這種情況有點傷腦筋,待研究。

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

補:解決了,和相關人員對照 Server 端的 CODE 後,Client 端

public List<VerifyData> data { get; set; }

改成

public VerifyData data { get; set; }

其實 RestSharp 106 不該讓上面通過,它是錯誤的;結果到了 RestSharp v107 才判斷出它是錯的。

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

(完)

相關

[研究][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]用 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



[研究][ASP.NET]用 HttpClientFactory 做 RESTful API 呼叫(二)模組化

[研究][ASP.NET]用 HttpClientFactory 做 RESTful API 呼叫(二)模組化

2023-03-27

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

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

Web.Config 設定一些變數值

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="ProductRestfulURL" value="https://www.ncert.nat.gov.tw/" />
    <add key="Account" value="帳號" />
    <add key="Pass" value="密碼" />
  </appSettings>
</configuration>

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

建立 Models 目錄,加入/新增項目,選程式碼,選類別,把 Class1.cs 改名 MyMoldel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class MyModel
    {
    }
	public class ProductListResult
    {
        public string message { get; set; }
        public string describe { get; set; }
        public List<ProductListData> data { get; set; }
    }

    public class ProductListData
    {
	public string product_id { get; set; }
        public string product_name { get; set; }
        public string product_level { get; set; }
        public string product_official_type { get; set; }
        public string product_type { get; set; }
        public string product_sub_type { get; set; }
        public string product_adjust_note { get; set; }
    }
}


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

建立 Logic 目錄,加入/新增項目,選程式碼,選類別,把 Class1.cs 改名 ProductHttpClientFactoryClient.cs

using Newtonsoft.Json;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
using WebApplication1.Models;

namespace WebApplication1.Logic
{
    public class ProductHttpClientFactoryClient
    {
        static readonly string productRestfulURL = ConfigurationManager.AppSettings["ProductRestfulURL"];
static readonly string productRestfulAccount = ConfigurationManager.AppSettings["Account"]; static readonly string productRestfulPass = ConfigurationManager.AppSettings["Pass"];
        public static async Task<GetUnitListResult> GetUnitListResult()
        {

            var data = new Dictionary<string, string>
                {
                    { "code", productRestfulAccount },
{ "pass", productRestfulPass },
}; HttpClient client = System.Net.Http.HttpClientFactory.Create(); string url = "https://www.xxx.idv.tw/rest/getProductList"; var content = new FormUrlEncodedContent(data); var response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { var responseVerifyResultString = await response.Content.ReadAsStringAsync(); GetUnitListResult responseUnitListResultJson = JsonConvert.DeserializeObject<GetUnitListResult>(responseVerifyResultString); return responseUnitListResultJson; } else { return null; } } } }

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

Default4.aspx

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

<!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:Label ID="Label1" runat="server" Text=""></asp:Label>
        </div>
    </form>
</body>
</html>


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

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

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

Default4.aspx.cs

using System;
using WebApplication1.Logic;
using WebApplication1.Models;

namespace WebApplication1
{

    public partial class Default4 : System.Web.UI.Page
    {
        protected async void Page_Load(object sender, EventArgs e)
        {
            GetProductListResult responseProductListResult = await ProductHttpClientFactoryClient.GetProductListResult();
            string responseProductListResult_message = responseProductListResult.message;
            Label1.Text = responseProductListResult_message;
        }
    }
}

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

(完)

相關

[研究][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]用 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



2023年3月2日 星期四

[研究][ASP.NET]用 HttpClientFactory 做 RESTful API 呼叫(一)

[研究][ASP.NET]用 HttpClientFactory 做 RESTful API 呼叫(一)

2023-03-02

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

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

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>
        </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.Net.Http;

namespace WebApplication1
{

    public partial class Default : System.Web.UI.Page
    {
        public class ObjectResult
        {
            public string message { get; set; }
            public string describe { get; set; }
            public List<ObjectData> data { get; set; }
        }

        public class ObjectData
        {
            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; }

        }
        protected async void Page_Load(object sender, EventArgs e)
        {
            // 建立要傳送的資料
            var data = new Dictionary<string, string>
                {
                    { "code", "帳號" },
                    { "pass", "密碼" }
                };
            HttpClient client = HttpClientFactory.Create();
            string url = "https://網址/rest/getObjectList";

            //var content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json");
            //HttpResponseMessage response = await client.PostAsJsonAsync(url, content);

            var content = new FormUrlEncodedContent(data);
            var response = await client.PostAsync(url, content);    
            if (response.IsSuccessStatusCode)
            {
                var resultString = await response.Content.ReadAsStringAsync();
                var resultObj = JsonConvert.DeserializeObject<ObjectResult>(resultString);
                //Label1.Text = "Response: " + result;
                Response.Write(resultObj.message);
                Response.Write(resultObj.describe);
                foreach (var dd in resultObj.data)
                {
                    Response.Write(dd.product_name + "," + dd.product_level + "<br />");
                }
            }
            else
            {
                Label1.Text = "Error: " + response.StatusCode;
            }
        }
    }
}

這是一個敝人實際測試過,真實可用的 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



[研究]ASP.NET RESTful API: 比較 HTTPClient , RestSharp , WebClient, HttpClientFactory, Flurl, Refit, RestEase

[研究]ASP.NET RESTful API: 比較 HTTPClient , RestSharp , WebClient, HttpClientFactory, Flurl, Refit, RestEase

2023-03-01

RestSharp v107程式寫法大改,網路上不少人踢到鐵板,連 ChatGPT 給的 Code 百般詢問,也無一能正常運作,不過可以拿來問問一些資訊。

(不過 ChatGPT 的資訊不保證 100% 正確 )

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

Q:ASP.NET RESTful API: 比較 HTTPClient , RestSharp , WebClient, HttpClientFactory, Flurl, Refit, RestEase

ChatGPT:

這些庫都提供了一些用於在.NET中支援RESTful API的功能,但是它們之間有一些不同之處。以下是這些庫的一些比較:

  • WebClient:2003年發布,WebClient是.NET Framework 1.1自帶的一個用於發送HTTP請求的類。它提供了一些基本的功能,例如:發送GET和POST請求、下載文件等。
  • RestSharp:2010年發布,RestSharp是一個流行的.NET庫,用於處理RESTful API。它提供了一些方便的功能,例如:自動序列化和反序列化JSON數據、處理HTTP錯誤、使用不同的身份驗證方案等。
  • HttpClient: 2012 年發布,是 .NET Framework 4.5 和 .NET Core 的一部分,提供了一些用於發送HTTP請求的基本功能。它可以通過HTTP/HTTPS協議與Web伺服器通訊,支援異步操作,具有較高的性能和可擴展性。
  • Flurl: 2016 年發布,Flurl是一個.NET庫,用於處理URL和HTTP請求。它提供了一些方便的功能,例如:使用流暢的API構建URL、發送HTTP請求、處理HTTP錯誤等。
  • Refit: 2016 年發布,Refit是一個.NET庫,用於處理RESTful API。它提供了一些方便的功能,例如:使用介面定義API、自動序列化和反序列化JSON數據、處理HTTP錯誤、使用不同的身份驗證方案等。
  • RestEase: 2017年發布,RestEase是一個.NET庫,用於處理RESTful API。它提供了一些方便的功能,例如:使用介面定義API、自動序列化和反序列化JSON數據、處理HTTP錯誤、使用不同的身份驗證方案等。
  • HttpClientFactory:2018年發布,是 .NET Core 2.1 中引入的,HttpClientFactory是一個用於 .NET 的簡單 REST 和 HTTP API 客戶端,用於創建和管理HttpClient實例。它提供了一些方便的功能,例如:管理HTTP連接、處理HTTP錯誤、使用不同的身份驗證方案等。
總的來說,這些庫都提供了一些類似的功能,但是它們的重點和重點功能略有不同。選擇最合適的庫取決於您的具體需求和項目的特定要求。

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

Q:請問 HTTPClient , RestSharp , WebClient, HttpClientFactory, Flurl, Refit, RestEase 是否都支援 ASP.NET WebForm ?

ChatGPT:

這些套件大部分都是針對 Web API 或是 ASP.NET Core 開發的,但有些也支援在 ASP.NET WebForm 上使用。以下是這些套件支援 ASP.NET WebForm 的情況:

  • HTTPClient: 支援在 ASP.NET WebForm 上使用。
  • RestSharp: 支援在 ASP.NET WebForm 上使用。
  • WebClient: 支援在 ASP.NET WebForm 上使用。
  • HttpClientFactory: 不支援在 ASP.NET WebForm 上使用。
  • Flurl: 不支援在 ASP.NET WebForm 上使用。
  • Refit: 不支援在 ASP.NET WebForm 上使用。
  • RestEase: 不支援在 ASP.NET WebForm 上使用。

需注意的是,某些套件可能需要特定版本的 .NET Framework 或 NuGet 套件,因此在使用之前應該先檢查其相關的文件與要求。

敝人補充說明:敝人後來請 ChatGPT 給 HttpClientFactory 的 ASP.NET, WebForm, C#, 程式範例,ChatGPT 卻給了,矛盾。

程式實際上編譯失敗,不能用,但 NuGet 安裝 Microsoft.AspNet.WebApi.Client 套件後,void Page_Load 前面加上 async,<%@ Page Language="C#" 之後加上 Async="true" ,是可以執行的。

也就是是否支援 ASP.NET WebForm 部分,正確性有待確認。

使用 HttpClientFactory 實作復原 HTTP 要求 | Microsoft Learn
https://learn.microsoft.com/zh-tw/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

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

Q:ASP.NET, WebForm, C#, RESTful, 請比較 HTTPClient, RestSharp, WebClient

ChatGPT:

HTTPClient、RestSharp和WebClient都是用於在C# ASP.NET應用程序中實現RESTful服務的庫。

以下是這些庫之間的比較:

HTTPClient:

  • 是 .NET Framework 和 .NET Core 中的標準庫,不需要額外安裝。
  • 提供了比較高層次的抽象,可以透過HttpClient實例進行HTTP請求,例如 GET, POST, PUT, DELETE 等。
  • 可以使用HttpContent進行非文本內容的處理,並且可以在 HttpClientHandler 中設置一些選項,例如:Timeout、MaxConnectionsPerServer、Proxy 等。
  • 對於RESTful服務,HTTPClient的使用非常方便,通常是最好的選擇。

RestSharp:

  • 是一個獨立的開源庫,需要通過NuGet安裝。
  • 提供了與HTTP相關的類和方法,但是與HTTPClient相比,它更注重於 RESTful 服務的操作。
  • RestSharp為使用者提供了簡單的設定選項,例如:BaseUrl、RequestFormat、JsonSerializer、XmlSerializer 等。
  • 對於較複雜的RESTful服務,RestSharp的使用可能會比HttpClient更方便。

WebClient:

  • 是 .NET Framework 中的標準庫,不需要額外安裝。
  • 是比較老的庫,一般用於執行簡單的HTTP請求,例如下載文件或讀取HTML內容。
  • WebClient不支持許多高級的HTTP選項,例如Timeout和最大連接數,因此對於高流量的RESTful服務可能不是最佳選擇。

總的來說,如果你需要進行RESTful服務的操作,那麼HTTPClient和RestSharp都是不錯的選擇,具體使用哪一個取決於你的需求。WebClient則更適合執行簡單的HTTP請求。

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

Q:比較 HTTPClient 和 RestSharp ?

ChatGPT:

HTTPClient 和 RestSharp 都是 .NET 中常用的用於發送 HTTP 請求的庫。它們都可以用來執行類似的任務,但是它們在某些方面有所不同。以下是它們之間的比較:

語法和用法:

  • HTTPClient 是 .NET 框架中的內置類,因此在使用時無需安裝額外的套件。使用 HTTPClient,您可以通過一些基本的方法,例如 GetAsync、PostAsync、PutAsync 等,輕鬆地發送 HTTP 請求。
  • RestSharp 是一個第三方庫,必須通過 NuGet 套件管理器安裝。它提供了一些額外的功能,例如支援多種數據格式,以及內置序列化和反序列化功能。RestSharp 還提供了一個 Fluent API,可以幫助您輕鬆地創建和修改 HTTP 請求。

支援的數據格式:

  • HTTPClient 只支援 JSON 和 XML 數據格式,您需要自己編寫代碼處理其他格式。
  • RestSharp 支援多種數據格式,例如 JSON、XML、CSV 和二進制數據格式。它還提供了內置的序列化和反序列化功能,可以將數據轉換為對象或從對象轉換為數據。

性能:

  • 由於 HTTPClient 是 .NET 框架中的內置類,因此它的性能通常比 RestSharp 更快。但是,如果您需要處理大量的請求或者需要支援多種數據格式,則 RestSharp 可能更適合您的需求。

總體而言,HTTPClient 和 RestSharp 都是優秀的庫,可以幫助您發送 HTTP 請求。您可以根據自己的需求選擇其中之一。如果您需要支援多種數據格式或需要一個更方便的 API,那麼 RestSharp 可能更適合您。如果您只需要簡單地發送 HTTP 請求,那麼 HTTPClient 可能更適合您。

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

Q:比較 HTTPClient 和 RestSharp 差異?優點?缺點?

ChatGPT:

HTTPClient 和 RestSharp 都是在 .NET 平台上使用的用於發送 HTTP 請求的程式庫。

差異:

  • HTTPClient 是 .NET 原生的程式庫,而 RestSharp 則是第三方程式庫。
  • HTTPClient 比 RestSharp 更加輕量,因為它是原生程式庫,而 RestSharp 有更多的功能和依賴程式庫。
  • RestSharp 提供更多的便利性功能,例如支持 XML 和 JSON 的自動序列化和反序列化等等。

優點:

  • HTTPClient:原生程式庫,輕量且簡單易用。
  • RestSharp:提供了更多的便利性功能,如自動序列化和反序列化,以及支持多種數據格式等等。

缺點:

  • HTTPClient:功能比 RestSharp 簡單。
  • RestSharp:依賴程式庫較多,使用時需要額外引用。

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

相關

HTTPClient: https://docs.microsoft.com/zh-tw/dotnet/api/system.net.http.httpclient?view=net-6.0

RestSharp: https://restsharp.dev/

WebClient: https://docs.microsoft.com/zh-tw/dotnet/api/system.net.webclient?view=net-6.0

Flurl.Http: https://flurl.dev/docs/flurl-http/

Refit: https://github.com/reactiveui/refit

RestEase: https://github.com/canton7/RestEase

HttpClientFactory: https://docs.microsoft.com/zh-tw/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

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

比較 HttpClientFactory, HTTPClient 和 RestSharp

ChatGPT:

  • HttpClientFactory、HttpClient和RestSharp都是用於在.NET應用程序中執行HTTP請求的庫。以下是它們的比較:
  • HttpClientFactory是一個工廠模式,可以用來創建和管理HttpClient對象。這個庫允許您在應用程序中重用HttpClient對象,以減少資源的浪費和改善性能。HttpClientFactory還提供了一個可擴展的管道系統,允許您添加自定義中間件以擴展HTTP請求的處理。
  • HttpClient是一個輕量級的庫,用於執行HTTP請求。HttpClient允許您輕鬆地向Web服務器發送HTTP請求並處理它們的響應。使用HttpClient,您可以輕鬆地處理JSON,XML等格式的資料。
  • RestSharp是一個簡單而強大的庫,用於執行RESTful API的HTTP請求。它允許您快速輕鬆地發送請求和處理響應。RestSharp支持多種請求方法,例如GET、POST、PUT和DELETE。此外,它還支持參數的序列化和反序列化,例如JSON、XML等。

總的來說,HttpClientFactory可以幫助您提高性能和資源的管理,而HttpClient和RestSharp則可以讓您快速輕鬆地執行HTTP請求。選擇哪一個庫取決於您的具體需求和應用程序的要求。

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

比較 HttpClientFactory, HTTPClient 和 RestSharp 差異 ? 優點 ? 缺點  ?

ChatGPT:

以下是HttpClientFactory、HttpClient和RestSharp的比較,包括它們的差異、優點和缺點:

HttpClientFactory

  • 差異:HttpClientFactory是一個工廠模式,用於創建和管理HttpClient對象。它可以在應用程序中重用HttpClient對象,提高性能和資源管理。它還提供一個可擴展的管道系統,允許您添加自定義中間件以擴展HTTP請求的處理。
  • 優點:使用HttpClientFactory可以減少資源的浪費,提高性能,以及允許您以簡單的方式添加自定義中間件。
  • 缺點:可能需要一些額外的學習成本來瞭解如何使用HttpClientFactory。

HttpClient

  • 差異:HttpClient是一個輕量級的庫,用於執行HTTP請求。它可以輕鬆地向Web服務器發送HTTP請求並處理它們的響應。它支持多種請求方法和資料格式。
  • 優點:HttpClient易於使用,並且支持多種請求方法和資料格式。它還提供了一些高級功能,例如取消和超時。
  • 缺點:在大量請求的情況下,HttpClient可能會耗盡資源,並且需要注意資源管理。

RestSharp

  • 差異:RestSharp是一個用於執行RESTful API的HTTP請求的庫。它提供了一些高級功能,例如自動序列化和反序列化,以及對OAuth和多部分表單等協議的支持。
  • 優點:RestSharp易於使用,並且提供了一些高級功能。它支持多種請求方法和資料格式。
  • 缺點:RestSharp可能比HttpClient更慢一些,並且不如HttpClientFactory提供性能和資源管理方面的優化。

綜合來看,HttpClientFactory提供了性能和資源管理方面的優化,HttpClient提供了易用性和高級功能,而RestSharp則提供了易用性和高級功能。選擇哪個庫取決於您的具體需求和應用程序的要求。

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

比較 HttpClientFactory, HTTPClient 和 RestSharp 問世年代 ?

ChatGPT:

HttpClient和HttpClientFactory是在.NET Framework 4.5和.NET Core 2.1中引入的。HttpClientFactory在.NET Core 2.1中首次出現,而HttpClient在.NET Framework 4.5中首次出現。這些庫都是現代的HTTP庫,可以用於發送和接收HTTP請求和響應。

RestSharp是一個第三方庫,於2010年首次發佈。它是一個針對RESTful API的HTTP庫,提供了對OAuth和多部分表單等協議的支持,以及自動序列化和反序列化等高級功能。RestSharp已經有一段時間沒有更新了,但它仍然是一個非常流行的HTTP庫。

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

請問 .NET Framework 4.5和.NET Core 2.1 問世年代

ChatGPT:

.NET Framework 4.5於2012年8月15日發佈,是一個用於Microsoft Windows的開發平台。它包含了一個可重用的程式碼庫,用於編寫應用程序,其中包括了多種語言,例如C#、VB.NET和F#等。

.NET Core 2.1於2018年5月30日發佈,是一個開源的、跨平台的.NET開發平台。它可以在Windows、macOS和Linux等多個平台上運行,並且可以用於構建Web應用程序、RESTful服務、遊戲、桌面應用程序和行動應用程序等不同類型的應用程序。

總體來說,.NET Framework 4.5和.NET Core 2.1都是Microsoft的.NET平台中的一部分,它們分別於2012年和2018年問世,是.NET平台的不同版本。

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

請問微軟有推薦 HttpClientFactory, HTTPClient 和 RestSharp 誰取代誰 ? 網址 ?

ChatGPT:

微軟在官方文件中建議使用HttpClient和HttpClientFactory,這是.NET Framework和.NET Core中的一個現代HTTP客戶端庫。在官方文件中,HttpClientFactory被描述為「創建和配置HttpClient實例的首選方法」。

微軟並沒有針對RestSharp進行官方的推薦或是建議,因為RestSharp是一個第三方庫。但是,如果您需要使用RestSharp的高級功能,那麼RestSharp仍然是一個很好的選擇。

以下是相關的官方文件連結:

HttpClientFactory: https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

HttpClient: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient

RestSharp: https://restsharp.dev/

敝人補充對應的繁體中文網址:

https://learn.microsoft.com/zh-tw/dotnet/api/system.net.http.httpclient?view=net-7.0

https://learn.microsoft.com/zh-tw/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

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

微軟對 HTTPClient  和 HttpClientFactory的評比 ?

微軟認為,HttpClient 是 .NET 中的一個非常重要的組件,它允許應用程序輕鬆地進行 HTTP 請求和響應。但是,在 .NET Core 2.1 之前,使用 HttpClient 的方式可能會導致內存洩漏和性能問題,特別是當應用程序需要頻繁地進行 HTTP 請求時。

為了解決這些問題,微軟在 .NET Core 2.1 中引入了 HttpClientFactory。 HttpClientFactory 是一個用於創建和管理 HttpClient 實例的工廠,它提供了一種更可靠和可維護的方式來處理 HTTP 請求和響應。通過 HttpClientFactory,應用程序可以更好地控制 HttpClient 實例的生命週期,從而避免內存洩漏和性能問題。

綜上所述,微軟認為 HttpClientFactory 是更好的選擇,因為它可以提供更好的性能和可維護性。但是,HttpClient 仍然是一個很好的組件,可以在某些情況下使用。如果您需要輕鬆地進行 HTTP 請求和響應,並且不需要頻繁地進行這些操作,那麼使用 HttpClient 是一個很好的選擇。

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

評比來源網址 ?

這個評比是基於我的知識和經驗做出的,並沒有一個特定的來源網址。這是我根據我的理解和知識做出的結論。如果您需要更多關於 HttpClient 和 HttpClientFactory 的信息,我建議您參考微軟的官方文檔,其中有更詳細的信息和指導。

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

(完)

相關

[研究][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


[研究][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