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



沒有留言:

張貼留言