在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
RestSharp 是一個受歡迎的開源 .NET 庫,用於在 C# 中發送 HTTP 請求。它簡化了與 RESTful API 一起使用的過程,提供了一種與 Web 服務通信的直接而靈活的方法。在本文中,我們將探討 的關鍵特徵。 RestSharp 和 IronPDF 並演示如何讓您能夠處理數據並生成PDF。
在現代多層應用程式中,不同的服務經常需要相互通信,而 RestSharp 提供了一種簡單而高效的方式,通過封裝所有的複雜性。這大大簡化了軟體開發過程。
RestSharp 可用作 NuGet 可以安裝在您的 C# 設計中。您可以使用 NuGet 套件管理器控制台來完成這個操作。 Visual Studio NuGet 套件管理器 UI。
Install-Package RestSharp
讓我們從一個簡單的例子開始,使用 RestSharp 向 RESTful API 發出 GET 請求。假設我們想要從一個返回用戶數據的公共 ASP.NET Core API 獲取信息:
using RestSharp;
namespace rest_sharp_demo;
class Program
{
static void Main()
{
// Create a RestClient instance
var baseUrl = "https://jsonplaceholder.typicode.com/users";
RestClientOptions options = new RestClientOptions(baseUrl)
{UseDefaultCredentials = true};
var client = new RestClient(options);
// Create a RestRequest for the GET method
var request = new RestRequest();
// Execute the request and get the response
var response = client.Get(request);
// Check if the request was successful
if (response.IsSuccessful)
{
// Output the response body content
Console.WriteLine(response.Content);
}
else
{
// Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
public void LogData(string msg)
{
Console.WriteLine(msg)
}
}
using RestSharp;
namespace rest_sharp_demo;
class Program
{
static void Main()
{
// Create a RestClient instance
var baseUrl = "https://jsonplaceholder.typicode.com/users";
RestClientOptions options = new RestClientOptions(baseUrl)
{UseDefaultCredentials = true};
var client = new RestClient(options);
// Create a RestRequest for the GET method
var request = new RestRequest();
// Execute the request and get the response
var response = client.Get(request);
// Check if the request was successful
if (response.IsSuccessful)
{
// Output the response body content
Console.WriteLine(response.Content);
}
else
{
// Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
public void LogData(string msg)
{
Console.WriteLine(msg)
}
}
Imports RestSharp
Namespace rest_sharp_demo
Friend Class Program
Shared Sub Main()
' Create a RestClient instance
Dim baseUrl = "https://jsonplaceholder.typicode.com/users"
Dim options As New RestClientOptions(baseUrl) With {.UseDefaultCredentials = True}
Dim client = New RestClient(options)
' Create a RestRequest for the GET method
Dim request = New RestRequest()
' Execute the request and get the response
Dim response = client.Get(request)
' Check if the request was successful
If response.IsSuccessful Then
' Output the response body content
Console.WriteLine(response.Content)
Else
' Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}")
End If
End Sub
Public Sub LogData(ByVal msg As String)
Console.WriteLine(msg)
End Sub
End Class
End Namespace
RestSharp 也支援使用非同步 API 方法的非同步請求和響應。
RestSharp 提供了方便的方法,將響應內容反序列化為 C# 對象。讓我們擴展範例,將 JSON 響應數據反序列化為使用者對象列表:
// Deserialize JSON response into a list of User objects
var users = JsonSerializer.Deserialize<List<User>>(response.Content);
// Output user information
foreach (var user in users)
{
Console.WriteLine($"User ID: {user.Id}, Name: {user.Name}, Email:{user.Email}");
}
// Deserialize JSON response into a list of User objects
var users = JsonSerializer.Deserialize<List<User>>(response.Content);
// Output user information
foreach (var user in users)
{
Console.WriteLine($"User ID: {user.Id}, Name: {user.Name}, Email:{user.Email}");
}
' Deserialize JSON response into a list of User objects
Dim users = JsonSerializer.Deserialize(Of List(Of User))(response.Content)
' Output user information
For Each user In users
Console.WriteLine($"User ID: {user.Id}, Name: {user.Name}, Email:{user.Email}")
Next user
在此範例中,我們定義了一個帶有屬性對應到 JSON 欄位的 User 類別。我們使用了來自 "System.Text.Json.Serialization" 命名空間的 "JsonSerializer.Deserialize"。
public class User
{
[JsonPropertyName("company")]public Company Company { get; set; }
[JsonPropertyName("id")]public int Id { get; set; }
[JsonPropertyName("phone")]public string Phone { get; set; }
[JsonPropertyName("website")]public string Website { get; set; }
[JsonPropertyName("name")]public string Name { get; set; }
[JsonPropertyName("username")]public string Username { get; set; }
[JsonPropertyName("email")]public string Email { get; set; }
[JsonPropertyName("address")]public Address Address { get; set; }
}
public class User
{
[JsonPropertyName("company")]public Company Company { get; set; }
[JsonPropertyName("id")]public int Id { get; set; }
[JsonPropertyName("phone")]public string Phone { get; set; }
[JsonPropertyName("website")]public string Website { get; set; }
[JsonPropertyName("name")]public string Name { get; set; }
[JsonPropertyName("username")]public string Username { get; set; }
[JsonPropertyName("email")]public string Email { get; set; }
[JsonPropertyName("address")]public Address Address { get; set; }
}
Public Class User
<JsonPropertyName("company")>
Public Property Company() As Company
<JsonPropertyName("id")>
Public Property Id() As Integer
<JsonPropertyName("phone")>
Public Property Phone() As String
<JsonPropertyName("website")>
Public Property Website() As String
<JsonPropertyName("name")>
Public Property Name() As String
<JsonPropertyName("username")>
Public Property Username() As String
<JsonPropertyName("email")>
Public Property Email() As String
<JsonPropertyName("address")>
Public Property Address() As Address
End Class
所有的使用者ID和名稱都顯示在輸出中。
完整程式碼可以在 git 上取得 這裡.
RestSharp 支援發送 XML 或 JSON 主體請求。可以使用 RestRequest 實例的 AddJsonBody 或 AddXmlBody 方法來添加 JSON 或 XML 主體。RestSharp 會自動設置內容類型。
RestSharp 會自動處理 JSON 或 XML 響應。
//using RestSharp;
// Serialize the user object to JSON
var jsonBodyString = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request data
var requestData = new RestRequest().AddJsonBody(jsonBodyString);
var response=client.ExecutePost(requestData);
//using RestSharp;
// Serialize the user object to JSON
var jsonBodyString = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request data
var requestData = new RestRequest().AddJsonBody(jsonBodyString);
var response=client.ExecutePost(requestData);
'using RestSharp;
' Serialize the user object to JSON
Dim jsonBodyString = JsonSerializer.Serialize(newUser)
' Create a RestRequest for the POST method with the JSON request data
Dim requestData = (New RestRequest()).AddJsonBody(jsonBodyString)
Dim response=client.ExecutePost(requestData)
RestSharp也支援在請求正文中發送資料,這在创建或更新资源时很常见。我們來修改我們的範例以展示一個POST請求API:
using RestSharp;
var client = new RestClient("https://jsonplaceholder.typicode.com/users");
// New user object
var newUser = new User
{
Name = "John Doe",
Email = "john.doe@example.com"
};
// Serialize the user object to JSON
var jsonBody = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request body
var request = new RestRequest().AddJsonBody(jsonBody);
if (response.IsSuccessful)
{
// Output the response content
Console.WriteLine(response.Content);
}
else
{
Console.WriteLine($"Error: {response.ErrorMessage}");
}
using RestSharp;
var client = new RestClient("https://jsonplaceholder.typicode.com/users");
// New user object
var newUser = new User
{
Name = "John Doe",
Email = "john.doe@example.com"
};
// Serialize the user object to JSON
var jsonBody = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request body
var request = new RestRequest().AddJsonBody(jsonBody);
if (response.IsSuccessful)
{
// Output the response content
Console.WriteLine(response.Content);
}
else
{
Console.WriteLine($"Error: {response.ErrorMessage}");
}
Imports RestSharp
Private client = New RestClient("https://jsonplaceholder.typicode.com/users")
' New user object
Private newUser = New User With {
.Name = "John Doe",
.Email = "john.doe@example.com"
}
' Serialize the user object to JSON
Private jsonBody = JsonSerializer.Serialize(newUser)
' Create a RestRequest for the POST method with the JSON request body
Private request = (New RestRequest()).AddJsonBody(jsonBody)
If response.IsSuccessful Then
' Output the response content
Console.WriteLine(response.Content)
Else
Console.WriteLine($"Error: {response.ErrorMessage}")
End If
在此範例中,我們建立一個新的 User 物件資料,將其序列化為 JSON,並使用 AddJsonBody 方法將其包含在請求正文中。伺服器接收 JSON 資料並據此處理請求。
RestSharp 也支援發送帶有身份驗證的請求。RestClientOptions 參數可以包含身份驗證參數。
var options = new RestClientOptions("https://auth.net"){Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret)};
var options = new RestClientOptions("https://auth.net"){Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret)};
Dim options = New RestClientOptions("https://auth.net") With {.Authenticator = New HttpBasicAuthenticator(_clientId, _clientSecret)}
這裡我們使用基本的 clientId secret 驗證,這會在每個請求中發送。
RestSharp 可以處理 URL 請求過程中發生的錯誤,例如超時、身份驗證或授權錯誤。如果請求自動失敗,RestSharp 不會拋出異常。這需要手動配置。
可以進行以下錯誤處理配置。
ThrowOnDeserializationError:將此屬性設置為 true,將告知 RestSharp 當反序列化失敗時拋出異常。
var restClentOptions = new RestClientOptions(url) { ThrowOnAnyError = true };
var client = new RestClient(restClentOptions);
var restClentOptions = new RestClientOptions(url) { ThrowOnAnyError = true };
var client = new RestClient(restClentOptions);
Dim restClentOptions = New RestClientOptions(url) With {.ThrowOnAnyError = True}
Dim client = New RestClient(restClentOptions)
IronPDF 是一個來自 的 C# PDF 庫 Iron Software 幫助閱讀和生成 PDF 文件。它可以輕鬆地將帶有樣式信息的格式化文件轉換為 PDF。IronPDF 可以輕鬆地從 HTML 內容生成 PDF,還可以從 URL 下載 HTML 然後生成 PDF。
IronPDF 的一個主要功能是 HTML轉PDF, 保留所有佈局和樣式。它將網頁內容轉換為PDF,非常適合報告、發票和文檔。HTML文件、URL和HTML字符串可以輕鬆轉換為PDF。
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
立即開始在您的專案中使用IronPDF,並享受免費試用。
查看 IronPDF 上 Nuget 快速安裝和部署。已被下載超過800萬次,它正用C#改變PDF。
Install-Package IronPdf
請考慮安裝 IronPDF DLL 直接下載並手動安裝到您的專案或GAC表單: IronPdf.zip
手動安裝到您的項目中
下載DLL若要使用 NuGet 套件管理器將 IronPDF 整合到您的 Selenium RestSharp 專案中,請按照以下步驟操作:
如果您想通過套件管理器控制台將 IronPDF 包含在您的專案中,請在 Package Manager Console 中執行以下命令:
Install-Package IronPdf
這將會將 IronPDF 取回並安裝到您的專案中。
有关 IronPDF 的详细概述,包括其功能、兼容性和其他下载选项,请访问 NuGet 网站上的 IronPDF 页面:https://www.nuget.org/packages/IronPdf。
或者,您可以使用 dll 文件將 IronPDF 直接整合到您的項目中。從這裡下載包含 DLL 的 ZIP 文件 連結將其解壓縮,並將 DLL 包含在您的項目中。
現在我們將獲取所有用戶並使用 HTML 字符串和 IronPDF 生成器生成 PDF 報告。
using System.Text.Json;
using System.Text.Json.Serialization;
using RestSharp;
namespace rest_sharp_demo;
class Program
{
static void Main()
{
// Create a RestClient
var baseUrl = "https://jsonplaceholder.typicode.com/users";
RestClientOptions options = new RestClientOptions(baseUrl) { UseDefaultCredentials = true };
var client = new RestClient(options);
// Create a RestRequest for the GET method
var request = new RestRequest();
// Execute the request and get the response
var response = client.Get(request);
// Check if the request was successful
if (response.IsSuccessful)
{
// Deserialize JSON response into a list of User objects
var users = JsonSerializer.Deserialize<List<User>>(response.Content);
// Generate Pdf
var html = GetHtml(users);
var Renderer = new ChromePdfRenderer();
var PDF = Renderer.RenderHtmlAsPdf(html);
PDF.SaveAs("UsersReport.pdf");
}
else
{
// Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
private static string GetHtml(List<User>? users)
{
string header = $@"
<html>
<head><title>Users List</title></head>
<body>
";
var footer = @"
</body>
</html>";
var htmlContent = header;
foreach (var user in users)
{
htmlContent += $@"
<h1>{user.Name}</h1>
<p>Username: {user.Username}</p>
<p>Email: {user.Email}</p>
<p>Company: {user.Company}</p>
<p>Phone: {user.Phone}</p>
<p>Website: {user.Website}</p>
<p>Suite: {user.Address.Suite}</p>
<p>Street: {user.Address.Street}</p>
<p>City: {user.Address.City}</p>
<p>Zipcode: {user.Address.Zipcode}</p>
";
}
htmlContent += footer;
return htmlContent;
}
}
using System.Text.Json;
using System.Text.Json.Serialization;
using RestSharp;
namespace rest_sharp_demo;
class Program
{
static void Main()
{
// Create a RestClient
var baseUrl = "https://jsonplaceholder.typicode.com/users";
RestClientOptions options = new RestClientOptions(baseUrl) { UseDefaultCredentials = true };
var client = new RestClient(options);
// Create a RestRequest for the GET method
var request = new RestRequest();
// Execute the request and get the response
var response = client.Get(request);
// Check if the request was successful
if (response.IsSuccessful)
{
// Deserialize JSON response into a list of User objects
var users = JsonSerializer.Deserialize<List<User>>(response.Content);
// Generate Pdf
var html = GetHtml(users);
var Renderer = new ChromePdfRenderer();
var PDF = Renderer.RenderHtmlAsPdf(html);
PDF.SaveAs("UsersReport.pdf");
}
else
{
// Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
private static string GetHtml(List<User>? users)
{
string header = $@"
<html>
<head><title>Users List</title></head>
<body>
";
var footer = @"
</body>
</html>";
var htmlContent = header;
foreach (var user in users)
{
htmlContent += $@"
<h1>{user.Name}</h1>
<p>Username: {user.Username}</p>
<p>Email: {user.Email}</p>
<p>Company: {user.Company}</p>
<p>Phone: {user.Phone}</p>
<p>Website: {user.Website}</p>
<p>Suite: {user.Address.Suite}</p>
<p>Street: {user.Address.Street}</p>
<p>City: {user.Address.City}</p>
<p>Zipcode: {user.Address.Zipcode}</p>
";
}
htmlContent += footer;
return htmlContent;
}
}
Imports System.Text.Json
Imports System.Text.Json.Serialization
Imports RestSharp
Namespace rest_sharp_demo
Friend Class Program
Shared Sub Main()
' Create a RestClient
Dim baseUrl = "https://jsonplaceholder.typicode.com/users"
Dim options As New RestClientOptions(baseUrl) With {.UseDefaultCredentials = True}
Dim client = New RestClient(options)
' Create a RestRequest for the GET method
Dim request = New RestRequest()
' Execute the request and get the response
Dim response = client.Get(request)
' Check if the request was successful
If response.IsSuccessful Then
' Deserialize JSON response into a list of User objects
Dim users = JsonSerializer.Deserialize(Of List(Of User))(response.Content)
' Generate Pdf
Dim html = GetHtml(users)
Dim Renderer = New ChromePdfRenderer()
Dim PDF = Renderer.RenderHtmlAsPdf(html)
PDF.SaveAs("UsersReport.pdf")
Else
' Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}")
End If
End Sub
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: private static string GetHtml(List<User>? users)
Private Shared Function GetHtml(ByVal users As List(Of User)) As String
Dim header As String = $"
<html>
<head><title>Users List</title></head>
<body>
"
ignore ignore ignore ignore var footer = "
</body>
</html>"
ignore ignore var htmlContent = header
For Each user In users
htmlContent += $"
<h1>{user.Name}</h1>
<p>Username: {user.Username}</p>
<p>Email: {user.Email}</p>
<p>Company: {user.Company}</p>
<p>Phone: {user.Phone}</p>
<p>Website: {user.Website}</p>
<p>Suite: {user.Address.Suite}</p>
<p>Street: {user.Address.Street}</p>
<p>City: {user.Address.City}</p>
<p>Zipcode: {user.Address.Zipcode}</p>
"
ignore ignore ignore ignore ignore ignore ignore ignore ignore ignore ignore
Next user
htmlContent += footer
Return htmlContent
End Function
End Class
End Namespace
整個程式碼可以在 Git 中找到 這裡這裡我們首先從用戶列表生成一個HTML字符串,包含報告所需的所有格式。然後我們使用 IronPDF 生成一個PDF文檔。我們使用 "RenderHtmlAsPdf" 方法將HTML字符串轉換為PDF文檔。生成的文檔如下:
該文件有一個小型的水印,用於試用許可證,可以使用有效的許可證移除。
要使上述代碼生效,需要授權金鑰。此金鑰需放置在appsettings.json中。
"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
開發人員在註冊後可以獲得試用授權 這裡 是的,試用許可證不需要信用卡。只需提供電子郵件地址並註冊即可獲得免費試用。
RestSharp 函式庫簡化了在 C# 中使用 RESTful API 的過程,提供了一種乾淨且高效的方式進行 HTTP 請求和處理回應。不論是使用 GET 請求獲取數據,還是使用 POST 請求發送數據,RestSharp 直觀的 API 和便捷的功能使其成為開發與網絡服務交互應用程序的開發人員的寶貴工具。
IronPDF 提供靈活且易於使用的解決方案來生成PDF。如需更多有關IronPDF各項功能的資訊,請訪問文檔 頁面.
IronPDF 的永久 許可證 這可以幫助你提升程式碼技能並達到現代應用程式的要求。
了解RestSharp和IronPDF能增強技能,開發人員可以創建現代應用程式。