2023年3月27日 星期一

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



沒有留言:

張貼留言