GraphQL C#(對於開發者的運行原理)
GraphQL 作為 RESTful API 的替代方案,在建立彈性且有效率的 Web 服務方面已獲得極高的知名度。 GraphQL 可用於許多不同的語言,例如 Java、Python、ASP .NET Core。 但在這篇文章中,我們會深入探討在 C# 的情境中使用 GraphQL,以實際範例探索其概念、實作和用法。 此外,我們還將使用 IronPDF for C# 來借助 GraphQL 結構定義查詢類來建立 PDF 檔案。
什麼是 GraphQL?
GraphQL 是一種 API 的查詢語言,可讓客戶精確地請求所需的資料。 與 RESTful API 不同的是,RESTful API 的多個端點可能會傳回固定的資料結構,而 GraphQL 服務則允許客戶指定所需資料的形狀,因此更有效率也更有彈性。
Setting up GraphQL in C#
若要在 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
在這個例子中,我們定義了一個 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
Querying GraphQL from C#
現在,讓我們看看如何使用 GraphQL.Client NuGet 套件從 C# 用戶端查詢此 GraphQL API:
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
GraphQL C# 提供了強大且靈活的 API 設計方式,有了 HotChocolate 之類的函式庫,將 GraphQL 後端整合到 C# 應用程式就變得簡單直接。 透過定義模式和設定伺服器,您可以透過 GraphQL API 揭露資料,並從 C# 用戶端有效率地進行查詢。
輸出

Intro to IronPDF in C#
IronPDF 是一個多功能的 C# 函式庫,可讓您毫不費力地建立、編輯和處理 PDF 文件。 在本節中,我們將介紹 IronPDF,並示範如何將其與 GraphQL 結合使用,以產生動態 PDF 報告。
IronPDF 的優勢在於其HTML 轉 PDF 的功能,可保留所有版面與樣式。 它允許從網頁內容建立 PDF,非常適合報告、發票和文件。 HTML 檔案、URL 和 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
安裝 IronPDF。
要開始使用 IronPDF,請安裝 NuGet 套件:
Install-Package IronPdf
使用 IronPDF 利用 GraphQL 資料產生 PDF.
讓我們來建立一份 PDF 報告,從我們的 GraphQL API 抓取使用者資料,並以格式化的方式顯示。
範例
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
在這個例子中,我們使用 GraphQL 客戶端從我們的 GraphQL API 取得 helloWorld 訊息。 然後,我們建立一個包含此訊息的 HTML 模板,並使用 IronPDF 的 ChromePdfRenderer 將此 HTML 轉換為 PDF 檔案。
輸出

結論
GraphQL 已經成為 API 開發中的遊戲改變者,相較於傳統的 RESTful API,它提供了更靈活、更有效率的資料查詢與操作方式。GraphQL 允許用戶端僅要求他們所需的查詢資料類型,這使得它對於性能和靈活性至關重要的現代網路應用程式特別具有吸引力。
此外,將 GraphQL 與 IronPDF 等工具和套件結合,將為產生動態和資料驅動的 PDF 報告開啟一個令人振奮的可能性世界。 無論您是要建立發票、產生報告或製作任何其他類型的文件,在 C# 中整合 IronPDF 與 GraphQL,都能提供強大且有效率的方式來自動產生 PDF。
總而言之,GraphQL 與 C# 是建構現代化、靈活且有效率的 Web 應用程式的強大組合。 透過 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生成和操作功能。



