2024年4月27日 星期六

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(二)verify

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(二)verify

2024-04-27、2024-05-16

環境: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>



********************************************************************************

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Http;	// NuGet 安裝,HttpClient 要使用
using System.Threading.Tasks;

namespace WebApplication1
{

    public class VerifyResult
    {
        public string message { get; set; }
        public string describe { get; set; }

        // RestSharp v106 要這樣才能運作
        //public List<VerifyData> data { get; set; }

        // RestSharp v107 開始或 HttpClient ,要這樣才能運作
        public VerifyData data { get; set; }
    }

    public class VerifyData
    {
        public string product_class { get; set; }
        public string product_account { get; set; }
        public string product_name { get; set; }
        public string contact_account { get; set; }
        public string contact_name { get; set; }
        public string contact_cellphone { get; set; }
        public string contact_mail { get; set; }
        public string contact_dept { get; set; }
        public string contact_tel { get; set; }
        public string contact_extend { get; set; }
        public string contact_title { get; set; }
        public string status { get; set; }
        public List<string> contact_category { get; set; }
    }
    public partial class Default : System.Web.UI.Page
    {
        protected async void Page_Load(object sender, EventArgs e)
        {
            string account = "略";
            string password = "略";


            VerifyResult content = new VerifyResult();
            content = await Verify_by_HttpClient("1", account, password);
        }

        #region === public async static VerifyResult Verify_by_HttpClient(string account_type, string account, string password) ===
        public async static Task<VerifyResult> Verify_by_HttpClient(string account_type, string account, string password)
        {
            string iRESTfulUrl = ConfigurationManager.AppSettings["IRESTfulUrl"];
            string iRESTfulSysId = ConfigurationManager.AppSettings["IRESTfulSysId"];
            string iRESTfulSysPass = ConfigurationManager.AppSettings["IRESTfulSysPass"];
			string acc = TextBox_Acc.Text.Trim();
			string pass = TextBox_Pass.Text.Trim();
			
            var httpClient = new HttpClient();
            try
            {
//----------------------------------------------------
// 2024-05-16 補,發現回傳的 VerifyResult,如果成功 (0001) 和不成功的格式不同,VerifyData 是 [],
// 不成功的 在 VerifyResult v = serializer.Deserialize<VerifyResult>(jsonTextReader); 會出錯
/*
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WebApplication1.Models.VerifyData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. 
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. 
JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path 'data', line 1, position 68.
*/
// 只好做一個符合格式的
// 此問題在以前用 RestSharp v106 不會有
#region === 1 ===

var requestBody2 = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("sysid", iRESTfulSysId), new KeyValuePair<string, string>("syspass", iRESTfulSysPass), new KeyValuePair<string, string>("acc", acc), new KeyValuePair<string, string>("pass", pass), });
var response2 = await httpClient.PostAsync(WS_URL + "restful/verify", requestBody2);
                bool isSuccessStatusCode2 = response2.IsSuccessStatusCode;
                HttpResponseMessage ensureSuccessStatusCode2 = new HttpResponseMessage();
                if (isSuccessStatusCode2 == false)
                {
                    ensureSuccessStatusCode2 = response2.EnsureSuccessStatusCode();
                }

                var responseStream2A = response2.Content.ReadAsStreamAsync().Result;
                using (var responseStream2B = await response2.Content.ReadAsStreamAsync())
                {
                    using (StreamReader streamReader2B = new StreamReader(responseStream2B))
                    using (Newtonsoft.Json.JsonTextReader jsonTextReader2B = new Newtonsoft.Json.JsonTextReader(streamReader2B))
                    {
                        var json = streamReader2B.ReadToEnd(); // 讀取 JSON 資料到字串中
                        var jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
                        string message = jsonObject.message;
                        
                        if (message !="0001")
                        {
                            VerifyResult vv = new VerifyResult();
                            vv.message = message;
                            return vv;
                        }
                    }
                }
                #endregion
//----------------------------------------------------
var requestBody = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("sysid", iRESTfulSysId),
                    new KeyValuePair<string, string>("syspass", iRESTfulSysPass),
                    new KeyValuePair<string, string>("acc", acc),
                    new KeyValuePair<string, string>("pass", pass),
                });                var response2 = await httpClient.PostAsync(WS_URL + "restful/verify", requestBody);

var response = await httpClient.PostAsync(iRESTfulUrl + "restful/verify", requestBody); bool isSuccessStatusCode = response.IsSuccessStatusCode; HttpResponseMessage ensureSuccessStatusCode = new HttpResponseMessage(); if (isSuccessStatusCode == false) { ensureSuccessStatusCode = response.EnsureSuccessStatusCode(); } var responseStream2 = response.Content.ReadAsStreamAsync().Result; using (var responseStream = await response.Content.ReadAsStreamAsync()) { using (StreamReader streamReader = new StreamReader(responseStream)) using (Newtonsoft.Json.JsonTextReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { //不可以同時 ReadToEnd 和 Deserialize,只能擇一使用 //var json = streamReader.ReadToEnd(); // 讀取 JSON 資料到字串中 var serializer = new Newtonsoft.Json.JsonSerializer(); //return serializer.Deserialize<VerifyResult>(jsonTextReader); VerifyResult v = serializer.Deserialize<VerifyResult>(jsonTextReader); return v; } } } catch (HttpRequestException ex) { string exMsg = ""; if (ex != null) exMsg = ex.Message.ToString(); throw; } } #endregion } }

Default.aspx

<%@ Page Async="true" Language="C#" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

...(略)

實際測試,在 Visual Studio 中 Debug,v確實有拿到回傳資料。

(完)

相關

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(二)verify
https://shaurong.blogspot.com/2024/04/aspnetwebform-restsharp-10615_27.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



沒有留言:

張貼留言