跳至页脚内容
.NET 帮助

GraphQL C#(开发人员如何使用)

GraphQL 已成为替代 RESTful APIs 构建灵活高效网络服务的一种流行选择。 GraphQL 可用于许多不同的语言,如 Java、Python、ASP .NET core。 但在本文中,我们将深入探讨在 C# 环境中使用 GraphQL,探索其概念、实现和使用的实际示例。 同时,我们将使用 IronPDF for C# 来创建 PDF 文件,借助 GraphQL 架构定义查询类。

什么是GraphQL?

GraphQL 是 API 的查询语言,使客户端能够精确请求所需的数据。 与 RESTful APIs 不同,多个端点可能返回固定的数据结构,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

现在,让我们看看如何使用 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 - 运行先前代码的控制台输出

介绍 C# 中的 IronPDF

IronPDF 是一个多功能 C# 库,可轻松创建、编辑和操作 PDF 文档。 在本节中,我们将介绍 IronPDF,并演示如何结合 GraphQL 使用它生成动态 PDF 报告。

IronPDF 以其 HTML 到 PDF 的功能而闻名,能够保留所有布局和样式。 它允许从 Web 内容创建 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 APIs 相比,提供了一种更灵活和高效的方法来查询和操作数据。它能够让客户端仅请求所需的类型查询数据,这对于性能和灵活性至关重要的现代 Web 应用程序来说特别吸引人。

此外,将 GraphQL 与 IronPDF 等工具和包结合起来,为生成动态和数据驱动的 PDF 报告打开了令人兴奋的可能性。 无论您是在创建发票、生成报告还是生产其他类型的文档,将 IronPDF 与 C# 中的 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文档。

在C#项目中集成GraphQL涉及哪些步骤?

要将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#结合使用提供了灵活性和性能优势,允许高效的数据查询和操作,这对于构建现代网站应用程序是至关重要的。

如何安装IronPDF以在C#项目中使用?

通过NuGet包管理器使用命令:Install-Package IronPdf安装IronPDF到C#项目中。这允许您访问其PDF生成和操作功能。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。