.NET幫助 GraphQL C#(對於開發者的運行原理) Curtis Chau 更新日期:6月 22, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article GraphQL 作為構建靈活高效的網路服務的 RESTful API 替代方案,是受到顯著歡迎的方法之一。 GraphQL 有許多不同語言實現,例如 Java、Python、ASP .NET core。 但在本文中,我們將深入探討如何在 C# 環境中使用 GraphQL,探索其概念、實現和實際應用實例。 另外,我們將使用 IronPDF for C#,透過 GraphQL 結構定義查詢類來創建 PDF 文件。 什麼是 GraphQL? GraphQL 是一種用於 API 的查詢語言,使客戶端能夠精確請求所需的數據。 與可能返回固定數據結構的多個端點的 RESTful API 不同,GraphQL 服務允許客戶端指定所需的數據形狀,使其更加效率和靈活。 在 C# 中設置 GraphQL 要在 C# 項目中使用 GraphQL,您需要 HotChocolate 庫,一個熱門的 .NET GraphQL 端點服務器實現。 首先,安裝 Hot Chocolate NuGet 套件: Install-Package HotChocolate.AspNetCore 創建 GraphQL 架構 GraphQL 架構定義了您的 API 中可用的數據類型和操作。 下面是一個博客應用程序的架構優先實現的簡單示例: using HotChocolate.Types; public class QueryType : ObjectType { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Field("helloWorld") .Type<StringType>() .Resolve(context => "Hello, GraphQL!"); } } using HotChocolate.Types; public class QueryType : ObjectType { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Field("helloWorld") .Type<StringType>() .Resolve(context => "Hello, GraphQL!"); } } Imports HotChocolate.Types Public Class QueryType Inherits ObjectType Protected Overrides Sub Configure(ByVal descriptor As IObjectTypeDescriptor) descriptor.Field("helloWorld").Type(Of StringType)().Resolve(Function(context) "Hello, GraphQL!") End Sub End Class $vbLabelText $csharpLabel 在這個示例中,我們定義了一個 helloWorld 字段,當被查詢時返回字符串 "Hello, GraphQL!"。 創建 GraphQL 服務器 接下來,使用 ASP.NET Core 設置一個 GraphQL 服務器: using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddGraphQLServer() .AddQueryType<QueryType>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGraphQL(); }); } } using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddGraphQLServer() .AddQueryType<QueryType>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGraphQL(); }); } } Imports Microsoft.AspNetCore.Builder Imports Microsoft.AspNetCore.Hosting Imports Microsoft.Extensions.DependencyInjection Public Class Startup Public Sub ConfigureServices(ByVal services As IServiceCollection) services.AddGraphQLServer().AddQueryType(Of QueryType)() End Sub Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IWebHostEnvironment) app.UseRouting() app.UseEndpoints(Sub(endpoints) endpoints.MapGraphQL() End Sub) End Sub End Class $vbLabelText $csharpLabel 從 C# 查詢 GraphQL 現在,來看一下如何從 C# 客戶端查詢此 GraphQL API,使用 GraphQL.Client NuGet 套件: using GraphQL.Client.Http; using GraphQL.Client.Serializer.Newtonsoft; using System; using System.Threading.Tasks; // GraphQL query class to interact with the API public class Query { public static async Task Main() { // Set up the GraphQL client using var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions { EndPoint = new Uri("http://localhost:5000/graphql") // GraphQL endpoint }, new NewtonsoftJsonSerializer()); // Define the GraphQL query var request = new GraphQLRequest { Query = @" { helloWorld }" }; var response = await graphQLClient.SendQueryAsync<dynamic>(request); // Print the response from the GraphQL server Console.WriteLine((string)response.Data.helloWorld); } } using GraphQL.Client.Http; using GraphQL.Client.Serializer.Newtonsoft; using System; using System.Threading.Tasks; // GraphQL query class to interact with the API public class Query { public static async Task Main() { // Set up the GraphQL client using var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions { EndPoint = new Uri("http://localhost:5000/graphql") // GraphQL endpoint }, new NewtonsoftJsonSerializer()); // Define the GraphQL query var request = new GraphQLRequest { Query = @" { helloWorld }" }; var response = await graphQLClient.SendQueryAsync<dynamic>(request); // Print the response from the GraphQL server Console.WriteLine((string)response.Data.helloWorld); } } 'INSTANT VB NOTE: 'Option Strict Off' is used here since dynamic typing is used: Option Strict Off Imports GraphQL.Client.Http Imports GraphQL.Client.Serializer.Newtonsoft Imports System Imports System.Threading.Tasks ' GraphQL query class to interact with the API Public Class Query Public Shared Async Function Main() As Task ' Set up the GraphQL client Dim graphQLClient = New GraphQLHttpClient(New GraphQLHttpClientOptions With {.EndPoint = New Uri("http://localhost:5000/graphql")}, New NewtonsoftJsonSerializer()) ' Define the GraphQL query Dim request = New GraphQLRequest With {.Query = " { helloWorld }"} 'INSTANT VB NOTE: In the following line, Instant VB substituted 'Object' for 'dynamic' - this will work in VB with Option Strict Off: Dim response = Await graphQLClient.SendQueryAsync(Of Object)(request) ' Print the response from the GraphQL server Console.WriteLine(CStr(response.Data.helloWorld)) End Function End Class $vbLabelText $csharpLabel GraphQL C# 提供了一種強大而靈活的設計 API 的方式,並且隨著 HotChocolate 類似的庫,將 GraphQL 後端集成到 C# 應用程序變得簡單明了。 通過定義一個架構並設置一個服務器,您可以通過 GraphQL API 曝露您的數據,並從 C# 客戶端高效地查詢它。 輸出 介紹 IronPDF 在 C# 中的應用 IronPDF 是一個多功能的 C# 庫,允許您輕鬆創建、編輯和操作 PDF 文檔。 在這部分,我們將介紹 IronPDF,並演示如何結合 GraphQL 生成動態 PDF 報告。 IronPDF 凭借其 HTML 到 PDF 功能 脫穎而出,保持所有佈局和樣式。 它允許從網路內容創建 PDF,非常適合用於報告、發票和文檔。 HTML 文件、網址和 HTML 字符串可以無縫轉換為 PDF。 using IronPdf; class Program { static void Main(string[] args) { var renderer = new ChromePdfRenderer(); // 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"); // 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"); // 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(); // 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"); // 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"); // 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() ' 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") ' 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") ' 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 $vbLabelText $csharpLabel 安裝 IronPDF 要開始使用 IronPDF,安裝 NuGet 套件: Install-Package IronPdf 使用 GraphQL 數據生成 PDF 讓我們創建一個從我們的 GraphQL API 獲取用戶數據並以格式化方式顯示的 PDF 報告。 示例 using IronPdf; using GraphQL.Client.Http; using GraphQL.Client.Serializer.Newtonsoft; using System; using System.Threading.Tasks; public class PdfGenerator { public async Task GeneratePdfAsync() { // Initialize GraphQL client var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions { EndPoint = new Uri("http://localhost:5000/graphql") }, new NewtonsoftJsonSerializer()); // Define GraphQL query var query = new GraphQLRequest { Query = @" { helloWorld }" }; var response = await graphQLClient.SendQueryAsync<dynamic>(query); var helloMessage = response.Data.helloWorld.ToString(); // Create HTML content for the PDF var htmlContent = $@" <html> <head><title>GraphQL Report</title></head> <body> <h1>GraphQL Report</h1> <p>{helloMessage}</p> </body> </html>"; var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderHtmlAsPdf(htmlContent); pdf.SaveAs("GraphQLReport.pdf"); } } using IronPdf; using GraphQL.Client.Http; using GraphQL.Client.Serializer.Newtonsoft; using System; using System.Threading.Tasks; public class PdfGenerator { public async Task GeneratePdfAsync() { // Initialize GraphQL client var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions { EndPoint = new Uri("http://localhost:5000/graphql") }, new NewtonsoftJsonSerializer()); // Define GraphQL query var query = new GraphQLRequest { Query = @" { helloWorld }" }; var response = await graphQLClient.SendQueryAsync<dynamic>(query); var helloMessage = response.Data.helloWorld.ToString(); // Create HTML content for the PDF var htmlContent = $@" <html> <head><title>GraphQL Report</title></head> <body> <h1>GraphQL Report</h1> <p>{helloMessage}</p> </body> </html>"; var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderHtmlAsPdf(htmlContent); pdf.SaveAs("GraphQLReport.pdf"); } } 'INSTANT VB NOTE: 'Option Strict Off' is used here since dynamic typing is used: Option Strict Off Imports IronPdf Imports GraphQL.Client.Http Imports GraphQL.Client.Serializer.Newtonsoft Imports System Imports System.Threading.Tasks Public Class PdfGenerator Public Async Function GeneratePdfAsync() As Task ' Initialize GraphQL client Dim graphQLClient = New GraphQLHttpClient(New GraphQLHttpClientOptions With {.EndPoint = New Uri("http://localhost:5000/graphql")}, New NewtonsoftJsonSerializer()) ' Define GraphQL query Dim query As New GraphQLRequest With {.Query = " { helloWorld }"} 'INSTANT VB NOTE: In the following line, Instant VB substituted 'Object' for 'dynamic' - this will work in VB with Option Strict Off: Dim response = Await graphQLClient.SendQueryAsync(Of Object)(query) Dim helloMessage = response.Data.helloWorld.ToString() ' Create HTML content for the PDF Dim htmlContent = $" <html> <head><title>GraphQL Report</title></head> <body> <h1>GraphQL Report</h1> <p>{helloMessage}</p> </body> </html>" Dim renderer = New ChromePdfRenderer() Dim pdf = renderer.RenderHtmlAsPdf(htmlContent) pdf.SaveAs("GraphQLReport.pdf") End Function End Class $vbLabelText $csharpLabel 在這個示例中,我們使用 GraphQL 客戶端從我們的 GraphQL API 中提取 helloWorld 消息。 然後,我們構建一個包含此消息的 HTML 模板,並使用 IronPDF 的 ChromePdfRenderer 將此 HTML 轉換為一個 PDF 文件。 輸出 結論 GraphQL 已經成為 API 開發中的顛覆性技術,提供了一種比傳統 RESTful API 更靈活高效的數據查詢和操作方式。它能讓客戶端僅請求所需的查詢數據類型,這使其對於現代網路應用程序特別具有吸引力,因為性能和靈活性至關重要。 此外,將 GraphQL 與 IronPDF 之類的工具和套件結合使用,為生成動態和數據驅動的 PDF 報告開闢了令人興奮的可能性。 無論您是在創建發票、生成報告,還是製作任何其他類型的文檔,將 IronPDF 與 C# 中的 GraphQL 集成是一種自動化 PDF 生成的強大高效方式。 總而言之,GraphQL 和 C# 在構建現代靈活高效的網路應用程序方面是強大的組合。 擁有像 HotChocolate、GraphQL.Client 和 IronPDF 這樣的庫,開發人員擁有構建支持數據驅動的應用程序所需的所有工具,以滿足當今數字世界的需求。 HTML 到 PDF 的教程提供於以下 IronPDF 授權指南,供用戶使用。 常見問題解答 GraphQL如何與RESTful API不同? GraphQL允許客戶端請求所需的精確數據,減少RESTful API常見的過量獲取和欠量獲取。這種靈活性使其在查詢和操作數據方面更高效。 推薦使用哪個庫在C#中設置GraphQL伺服器? 推薦使用HotChocolate庫在C#中設置GraphQL伺服器。它提供了在.NET環境中定義模式和管理查詢的工具。 如何從GraphQL數據在C#中創建PDF報告? 您可以從GraphQL API抓取數據並使用IronPDF將數據轉換為動態PDF報告。IronPDF允許您通過將HTML內容轉換為PDF格式來操作PDF文檔。 將GraphQL集成到C#專案中涉及哪些步驟? 要將GraphQL集成到C#專案,安裝HotChocolate NuGet套件,定義一個大綱數據類型和操作的模式,並使用ASP.NET Core設置伺服器。 如何使用C#客戶端查詢GraphQL API? 使用GraphQL.Client NuGet套件設置一個帶有API端點URI的GraphQLHttpClient。定義您的查詢,並使用SendQueryAsync方法發送。 我可以在C#中將URL轉換為PDF嗎? 是的,您可以在C#中使用IronPDF的ChromePdfRenderer將URL轉換為PDF。它允許您直接將URL的HTML內容渲染為PDF文件。 為什麼將IronPDF與GraphQL結合使用於PDF創建? IronPDF可以將通過GraphQL獲取的動態HTML內容轉換為PDF,這對於需要更新和特定數據輸出的數據驅動報告非常理想。 如何在C#中創建基本的GraphQL模式? 要在C#中創建基本的GraphQL模式,使用HotChocolate庫的模式定義工具定義可用的數據類型和操作。這涉及到指定字段及其數據類型。 在Web應用中使用GraphQL與C#有哪些優勢? 將GraphQL與C#一起使用可以提供靈活性和性能優勢,允許高效的數據查詢和操作,這對於構建現代Web應用程序至關重要。 如何在C#專案中安裝IronPDF? 使用NuGet包管理器及命令:Install-Package IronPdf安裝IronPDF到C#專案。這樣可以訪問其PDF生成和操作功能。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# Call Base Constructor(對於開發者的運行原理)C# Long to String(對於開發者...