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



沒有留言:

張貼留言