跳至頁尾內容
開發者更新

GraphQL C#(對於開發者的運行原理)

GraphQL 以其作為替代 RESTful API 的靈活高效建構網路服務方式而受到廣泛關注。 GraphQL 有多種不同語言版本,如 Java、Python、ASP .NET core。 但在此文章中,我們將深入探討在 C# 中使用 GraphQL,探索其概念、實施和應用,並提供實際的例子。 此外,我們將使用 IronPDF for C# 配合 GraphQL 架構定義查詢類別來建立 PDF 文件。

什麼是 GraphQL?

GraphQL 是一種 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
$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

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
$vbLabelText   $csharpLabel

GraphQL C# 提供了一種設計 API 的強大而靈活的方式,使用 HotChocolate 等程式庫,將 GraphQL 後端整合到您的 C# 應用程式中變得更加簡單。 通過定義架構和設置伺服器,您可以通過 GraphQL API 曝露資料,並從 C# 客戶端高效地查詢它。

輸出

GraphQL C#(對開發者來說是如何運作的):圖1 - 運行前面程式的控制台輸出

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
$vbLabelText   $csharpLabel

安裝 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
$vbLabelText   $csharpLabel

在本範例中,我們使用 GraphQL 客戶端從我們的 GraphQL API 獲取 helloWorld 資訊。 然後,我們構建一個包含此消息的 HTML 模板,並使用 IronPDF 的 ChromePdfRenderer 將此 HTML 轉換為 PDF 文件。

輸出

GraphQL C#(對開發者來說是如何運作的):圖2 - 輸出來自前面程式碼的 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伺服器建議使用哪些程式庫?

在C#中設置GraphQL伺服器建議使用HotChocolate程式庫。它提供在.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套件設置一個GraphQLHttpClient,並指定API端點URI。定義您的查詢,然後使用SendQueryAsync方法發送查詢。

我可以在C#中將URL轉換為PDF嗎?

是的,您可以使用IronPDF的ChromePdfRenderer在C#中將URL轉換為PDF。它允許您將URL中的HTML內容直接呈現為PDF文件。

為何將IronPDF與GraphQL結合用於PDF建立?

IronPDF可以將通過GraphQL獲取的動態HTML內容轉換為PDF,這非常適合建立需要更新和特定資料輸出的資料驅動報告。

如何在C#中建立基本的GraphQL架構?

在C#中建立基本的GraphQL架構需要使用HotChocolate程式庫的架構定義工具定義可用的資料型別和操作。這涉及到指定欄位及其資料型別。

在網路應用程式中使用GraphQL與C#有什麼優勢?

使用GraphQL與C#提供了靈活性和性能優勢,允許有效的資料查詢和操作,這對於構建現代網路應用程式是必不可少的。

如何在C#專案中安裝IronPDF?

使用NuGet套件管理器安裝IronPDF到C#專案中,使用命令:Install-Package IronPdf。這樣可以存取其PDF生成和操作功能。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話