.NET 帮助

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

发布 2024年六月6日
分享:

简介

图形QL 作为 RESTful API 的替代品,GraphQL 在构建灵活高效的网络服务方面大受欢迎。GraphQL 可用于多种不同的语言,如 Java、Python 和 ASP .NET core。但在本文中,我们将深入探讨如何在 C# 环境中使用 GraphQL,并通过实际示例探索其概念、实现和用法。此外,我们还将使用 IronPDF 借助 GraphQL 模式定义查询类创建 PDF 文件。

什么是 GraphQL?

用于应用程序接口的 GraphQL 查询语言可让客户准确请求所需数据。与 RESTful API 不同的是,RESTful API 的多个端点可能会返回固定的数据结构,而 GraphQL 服务则允许客户指定所需数据的形状,从而使其更加高效和灵活。

在 C&num 中设置 GraphQL;

要在 C# 项目中使用 GraphQL,您需要 HotChocolate 库,它是一种流行的 .NET GraphQL 端点服务器实现。

首先,安装 Hot Chocolate NuGet 包:

Install-Package HotChocolate.AspNetCore

创建 GraphQL 模式

GraphQL 实现模式定义了 API 中可用的数据类型和操作。下面是一个简单的示例,首先是一个博客应用程序的 GraphQL 服务模式:

using HotChocolate.Types;
public class QueryType : ObjectType
{
    protected override void Configure(IObjectTypeDescriptor descriptor)
    {
        descriptor.Field("hello world")
            .Type<StringType>()
            .Resolve(context => "Hello, GraphQL!");
    }
}
using HotChocolate.Types;
public class QueryType : ObjectType
{
    protected override void Configure(IObjectTypeDescriptor descriptor)
    {
        descriptor.Field("hello world")
            .Type<StringType>()
            .Resolve(context => "Hello, GraphQL!");
    }
}
Imports HotChocolate.Types
Public Class QueryType
	Inherits ObjectType

	Protected Overrides Sub Configure(ByVal descriptor As IObjectTypeDescriptor)
		descriptor.Field("hello world").Type(Of StringType)().Resolve(Function(context) "Hello, GraphQL!")
	End Sub
End Class
VB   C#

在本例中,我们定义了一个你好世界字段,它返回一个字符串 "你好,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
VB   C#

从 C&num 查询 GraphQL;

现在,让我们看看如何使用 GraphQL.Client NuGet 包从 C# 客户端查询 GraphQL API:

using GraphQL.Client;
using GraphQL.Client.Http;
using System;
using System.Threading.Tasks;
// query class
public class query
{
    public static async Task Main()
    {
        using var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions
        {
            EndPoint = new Uri("http://localhost:5000/graphql")
        });
        var schema = new GraphQLRequest
        {
            Query = @"
                {
                    hello world
                }"
        };
        var response = await graphQLClient.SendQueryAsync<dynamic>(shema);
        Console.WriteLine(response.Data.hello);
    }
}
using GraphQL.Client;
using GraphQL.Client.Http;
using System;
using System.Threading.Tasks;
// query class
public class query
{
    public static async Task Main()
    {
        using var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions
        {
            EndPoint = new Uri("http://localhost:5000/graphql")
        });
        var schema = new GraphQLRequest
        {
            Query = @"
                {
                    hello world
                }"
        };
        var response = await graphQLClient.SendQueryAsync<dynamic>(shema);
        Console.WriteLine(response.Data.hello);
    }
}
'INSTANT VB NOTE: 'Option Strict Off' is used here since dynamic typing is used:
Option Strict Off

Imports GraphQL.Client
Imports GraphQL.Client.Http
Imports System
Imports System.Threading.Tasks
' query class
Public Class query
	Public Shared Async Function Main() As Task
		Dim graphQLClient = New GraphQLHttpClient(New GraphQLHttpClientOptions With {.EndPoint = New Uri("http://localhost:5000/graphql")})
		Dim schema = New GraphQLRequest With {.Query = "
                {
                    hello world
                }"}
'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)(shema)
		Console.WriteLine(response.Data.hello)
	End Function
End Class
VB   C#

GraphQL C# 为设计应用程序接口(API)提供了一种强大而灵活的方式,有了 HotChocolate 这样的库,将 GraphQL 后端集成到 C# 应用程序中就变得简单易行了。通过定义模式和设置服务器,您可以通过 GraphQL API 公开数据,并从 C# 客户端高效地查询数据。

输出

GraphQL C#(如何为开发人员工作):图 1 - 运行之前代码的控制台输出

C&num 中的 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();

        // 1. 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");

        // 2. 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");

        // 3. 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();

        // 1. 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");

        // 2. 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");

        // 3. 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()

		' 1. 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")

		' 2. 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")

		' 3. 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
VB   C#

安装 IronPDF

要开始使用 IronPDF,请安装 NuGet 软件包:

Install-Package IronPdf

使用 IronPDF 利用 GraphQL 数据生成 PDF

让我们创建一份 PDF 报告,从 GraphQL API 获取用户数据并以格式化的方式显示出来。

示例

using IronPdf;
using GraphQL.Client;
using GraphQL.Client.Http;
using System.Threading.Tasks;
using System;
public class PdfGenerator
{
    public async Task GeneratePdfAsync()
    {
        var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions
        {
            EndPoint = new Uri("http://localhost:5000/graphql")
        });
        // graphql queries & graphql requests
        var query = new GraphQLRequest 
        {
            Query = @"
                {
                    hello world
                }"
        };
        var response = await graphQLClient.SendQueryAsync<dynamic>(query);
        var helloMessage = response.Data.hello.ToString();
        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;
using GraphQL.Client.Http;
using System.Threading.Tasks;
using System;
public class PdfGenerator
{
    public async Task GeneratePdfAsync()
    {
        var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions
        {
            EndPoint = new Uri("http://localhost:5000/graphql")
        });
        // graphql queries & graphql requests
        var query = new GraphQLRequest 
        {
            Query = @"
                {
                    hello world
                }"
        };
        var response = await graphQLClient.SendQueryAsync<dynamic>(query);
        var helloMessage = response.Data.hello.ToString();
        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
Imports GraphQL.Client.Http
Imports System.Threading.Tasks
Imports System
Public Class PdfGenerator
	Public Async Function GeneratePdfAsync() As Task
		Dim graphQLClient = New GraphQLHttpClient(New GraphQLHttpClientOptions With {.EndPoint = New Uri("http://localhost:5000/graphql")})
		' graphql queries & graphql requests
		Dim query As New GraphQLRequest With {.Query = "
                {
                    hello world
                }"}
'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.hello.ToString()
		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
VB   C#

在本示例中,我们使用 GraphQL 客户端从 GraphQL API 获取 "你好世界 " 消息。然后,我们构建一个包含该消息的 HTML 模板,并使用 IronPDF 的 ChromePdfRenderer 将 HTML 转换为 PDF 文件。

输出

GraphQL C#(如何为开发人员工作):图 2 - 前面代码输出的 PDF

结论

与传统的 RESTful API 相比,GraphQL 提供了一种更灵活、更高效的数据查询和操作方法,从而改变了 API 开发的游戏规则。GraphQL 允许客户端只请求所需的查询数据类型,这对性能和灵活性要求极高的现代网络应用特别有吸引力。

此外,将 GraphQL 与诸如 IronPDF 为生成动态和数据驱动的 PDF 报告开辟了一个令人兴奋的可能性世界。无论您是创建发票、生成报告,还是制作其他任何类型的文档,将 IronPDF 与 C# 中的 GraphQL 集成在一起,都能为自动生成 PDF 提供强大而高效的方法。

总之,GraphQL 和 C# 是构建现代、灵活、高效网络应用程序的强大组合。有了 HotChocolate、"GraphQL.Client "和 IronPDF 等库,开发人员就拥有了构建强大的数据驱动型应用程序所需的所有工具,以满足当今数字环境的需求。

HTML 转 PDF 教程可从以下网站获取 链接 供用户使用。

< 前一页
C# 调用基类构造函数(开发人员如何实现)
下一步 >
C# Long 转换为 String(开发人员如何操作)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >