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




沒有留言:

張貼留言