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 服務則允許客戶指定所需資料的形狀,因此更有效率也更有彈性。
在 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在這個範例中,我們定義了一個 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從 C# 查詢 GraphQL;。
現在,讓我們看看如何使用 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 ClassGraphQL C# 提供了強大且靈活的 API 設計方式,有了 HotChocolate 之類的函式庫,將 GraphQL 後端整合到 C# 應用程式就變得簡單直接。 透過定義模式和設定伺服器,您可以透過 GraphQL API 揭露資料,並從 C# 用戶端有效率地進行查詢。
輸出

C#中的 IronPDF 入門;。
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 環境中定義模式和管理查詢的工具。
如何使用 C# 從 GraphQL 資料建立 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 嗎?
是的,您可以使用 IronPDF 的 ChromePdfRenderer 在 C# 中將 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 包管理器,使用命令為 C# 專案安裝 IronPdf:Install-Package IronPdf。這可讓您存取其 PDF 產生與處理功能。







