2022年2月26日 星期六

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API、JSON字串轉JSON Objection 測試(二)

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API、JSON字串轉JSON Objection 測試(二)

2022-02-26

續這篇

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)
http://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web.html

後來發現

HttpClient 類別
https://docs.microsoft.com/zh-tw/dotnet/api/system.net.http.httpclient?view=net-6.0&WT.mc_id=DOP-MVP-37580&viewFallbackFrom=netframework-4
HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
HttpClient 應該只建立一份並重複利用。為每次請求建立新的 HttpClient,重度使用下可能用光 Socket Port 導致 SocketException。以下是正確的寫法:

Visual Studio2022 v17.1.0 + ASP.NET + C# + Web Application + WebForm

Default.aspx


<%@ Page 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">
        <div>
            
        </div>
    </form>
    <asp:Label ID="Label_MSG1" runat="server" Text="Label"></asp:Label>
</body>
</html>

Default.aspx.cs


using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

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)
        {
            _ = CallWebAPI();
        }
        protected Task CallWebAPI()
        {
            string account = "帳號";
            string password = "密碼";
            var values = new[]
            {
                new KeyValuePair<string, string>("account", account),
                new KeyValuePair<string, string>("pass", password)
            };
            try
            {
                using (FormUrlEncodedContent multipartFormDataContent =
                    new FormUrlEncodedContent(values))
                {
                    //HttpResponseMessage response =
                    //    await client.PostAsync("https://網址/rest/verify", 
                    //        multipartFormDataContent);
                    //response.EnsureSuccessStatusCode();
                    //string responseBody = await response.Content.ReadAsStringAsync();
                    //string responseBody = await response.Content.ReadAsStringAsync();
                    //Label_MSG1.Text = responseBody;

                    var requestUri = "https://網址/rest/verify";
var json = client.PostAsync(requestUri, multipartFormDataContent).Result.Content.ReadAsStringAsync().Result; JObject jo = Newtonsoft.Json.Linq.JObject.Parse(json); string message = jo["message"].ToString(); string data = jo["data"].ToString(); string contact_account = jo["data"]["contact_account"].ToString(); Label_MSG1.Text = json;
// Above three lines can be replaced with new helper method below // string responseBody = await client.GetStringAsync(uri); } } catch (HttpRequestException ex) { Label_MSG1.Text = "不明錯誤。"; if (ex != null) Label_MSG1.Text = ex.Message.ToString(); } return Task.CompletedTask; } } }


(完)

相關

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


沒有留言:

張貼留言