[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫(一)成功
2023-03-02
環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C#
RsetSharp v107 程式寫法大改,相依套件非常多;目前最新已經到 108.0.3
https://restsharp.dev/v107/
網路上不少人踢到鐵板,敝人所有文章可轉貼,請註明來源,因為會不定時更新。
********************************************************************************
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 RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json.Serialization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public class GetObjectResult
{
public string message { get; set; }
public string describe { get; set; }
public List<GetObjectData> data { get; set; }
}
public class GetObjectData
{
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; }
}
public partial class Default : System.Web.UI.Page
{
// 注意,這裡要 async
protected async void Page_Load(object sender, EventArgs e)
{
// 請求的 API 網址
string apiUrl = "https://xxx.xxx.xxx.xxx/rest/getObjectList";
var ObjectResult = new GetObjectResult();
// 建立 RestSharp 的 HTTP 請求物件
// 敝人以 Postman 測試時,參數是加在 Body 才行,
// 但在本程式用 AddBody 收不到參數,要用 AddParamter 才行
var client = new RestClient(apiUrl);
var request = new RestRequest()
.AddHeader("Content-Type", "application/x-www-form-urlencoded")
.AddParameter("code", "帳號")
.AddParameter("pass", "密碼")
//.AddBody(
// new
// {
// code = "密碼",
// pass = "密碼"
// }
//)
//.AddBody(
// new Dictionary<string, string>
// {
// { "code", "帳號" },
// { "pass", "密碼" }
// }
//)
//.AddJsonBody(
// new
// {
// code = "帳號",
// pass = "密碼"
// }
//)
;
try
{
// 發送請求並取得回應
//----------------------------------------
RestResponse response0 = client.Execute(request);
//Response.Write(response0.Content+ "<br /><br />"); //成功
//var json0 = JsonConvert.SerializeObject(response0);
//Response.Write("Json0: " +json0+"<br /><br />"); // Fail Message
//----------------------------------------
var response = await client.PostAsync<GetObjectResult>(request);
//Response.Write(response.message);
var json = JsonConvert.SerializeObject(response);
//Response.Write("Json : " + json+ "<br /><br />"); // 成功
//----------------------------------------
var response2 = await client.ExecuteAsync<GetObjectResult>(request);
//Response.Write("response2.Data.message : " + response2.Data.message+ "<br /><br />"); // 成功
//----------------------------------------
var response3 = await client.ExecutePostAsync<GetObjectResult>(request);
//Response.Write(response.message);
var json3 = JsonConvert.SerializeObject(response3);
//Response.Write("Json3 : " + json3+ "<br /><br />"); // 成功
//----------------------------------------
var response4 = await client.PostAsync(request);
//Response.Write(response.message);
var json4 = JsonConvert.SerializeObject(response4);
//Response.Write("Json4 : " + json4+ "<br /><br />"); // 成功,但額外多一些怪資訊,因為沒有 Object 的 class
//----------------------------------------
var response5 = await client.PostAsync<GetObjectResult>(request);
//Response.Write(response.message);
var json5 = JsonConvert.SerializeObject(response5);
Response.Write("Json5 : " + json5 + "<br /><br />"); // 成功
//----------------------------------------
}
catch (Exception ex)
{
// Request failed with status code InternalServerError
Response.Write(ex.Message.ToString());
}
}
}
}
|
這是一個實際測試過,真實可用的 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
沒有留言:
張貼留言