Zum Fußzeileninhalt springen
.NET HILFE

GraphQL C# (Funktionsweise für Entwickler)

GraphQL has gained significant popularity as an alternative to RESTful APIs for building flexible and efficient web services. GraphQL is available in plenty of different languages, such as Java, Python, ASP .NET core. But in this article, we'll delve into using GraphQL in the context of C#, exploring its concepts, implementation, and usage with practical examples. Also, we will be using IronPDF for C# for creating PDF files with the help of the GraphQL schema definition query class.

What is GraphQL?

GraphQL is a query language for APIs that enables clients to request exactly the data they need. Unlike RESTful APIs, where multiple endpoints might return fixed data structures, GraphQL services allow clients to specify the shape of the data they require, making it more efficient and flexible.

Setting up GraphQL in C#

To use GraphQL in a C# project, you'll need the HotChocolate library, a popular GraphQL endpoint server implementation for .NET.

First, install the Hot Chocolate NuGet package:

Install-Package HotChocolate.AspNetCore

Creating a GraphQL Schema

A GraphQL schema defines the data types and operations available in your API. Here's a simple example of schema-first implementation for a blog application:

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

In this example, we define a helloWorld field that returns a string "Hello, GraphQL!" when queried.

Creating a GraphQL Server

Next, set up a GraphQL server using ASP.NET Core:

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#

Now, let's see how to query this GraphQL API from a C# client using the GraphQL.Client NuGet package:

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# offers a powerful and flexible way to design APIs, and with libraries like HotChocolate, integrating a GraphQL backend into your C# applications becomes straightforward. By defining a schema and setting up a server, you can expose your data through a GraphQL API and query it efficiently from C# clients.

Output

GraphQL C# (How It Works For Developers): Figure 1 - Console output from running the previous code

Intro to IronPDF in C#

IronPDF is a versatile C# library that allows you to create, edit, and manipulate PDF documents effortlessly. In this section, we'll introduce IronPDF and demonstrate how to use it in conjunction with GraphQL to generate dynamic PDF reports.

IronPDF excels with its HTML to PDF functionality, preserving all layouts and styles. It allows for PDF creation from web content, perfect for reports, invoices, and documentation. HTML files, URLs, and HTML strings can be seamlessly converted to PDFs.

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

Installing IronPDF

To get started with IronPDF, install the NuGet package:

Install-Package IronPdf

Generating PDF with GraphQL Data using IronPDF

Let's create a PDF report that fetches user data from our GraphQL API and displays it in a formatted manner.

Example

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

In this example, we use the GraphQL client to fetch the helloWorld message from our GraphQL API. Then, we construct an HTML template that includes this message and use IronPDF's ChromePdfRenderer to convert this HTML to a PDF file.

Output

GraphQL C# (How It Works For Developers): Figure 2 - Outputted PDF from the previous code

Conclusion

GraphQL has emerged as a game-changer in API development, offering a more flexible and efficient way to query and manipulate data compared to traditional RESTful APIs. Its ability to allow clients to request only the type query data they need makes it particularly appealing for modern web applications where performance and flexibility are paramount.

Moreover, combining GraphQL with tools and packages like IronPDF opens up a world of exciting possibilities for generating dynamic and data-driven PDF reports. Whether you're creating invoices, generating reports, or producing any other kind of documents, integrating IronPDF with GraphQL in C# provides a powerful and efficient way to automate PDF generation.

In summary, GraphQL and C# make a powerful combination for building modern, flexible, and efficient web applications. With libraries like HotChocolate, GraphQL.Client, and IronPDF, developers have all the tools they need to build robust, data-driven applications that meet the demands of today's digital landscape.

The HTML to PDF tutorial is available at the following IronPDF Licensing Guide for users to avail.

Häufig gestellte Fragen

Wie unterscheidet sich GraphQL von RESTful-APIs?

GraphQL ermöglicht es Clients, genau die Daten anzufordern, die sie benötigen, und reduziert somit das Über- und Unterabrufen, das typisch für RESTful-APIs ist. Diese Flexibilität macht es effizienter zum Abfragen und Manipulieren von Daten.

Welche Bibliothek wird zur Einrichtung eines GraphQL-Servers in C# empfohlen?

Die HotChocolate-Bibliothek wird zur Einrichtung eines GraphQL-Servers in C# empfohlen. Sie bietet Werkzeuge zur Definition von Schemata und zur Verwaltung von Abfragen innerhalb einer .NET-Umgebung.

Wie kann ich einen PDF-Bericht aus GraphQL-Daten in C# erstellen?

Sie können Daten von einer GraphQL-API abrufen und IronPDF verwenden, um die Daten in einen dynamischen PDF-Bericht zu konvertieren. IronPDF ermöglicht es Ihnen, PDF-Dokumente zu manipulieren, indem es HTML-Inhalte in das PDF-Format konvertiert.

Welche Schritte sind bei der Integration von GraphQL in ein C#-Projekt erforderlich?

Um GraphQL in ein C#-Projekt zu integrieren, installieren Sie das HotChocolate NuGet-Paket, definieren Sie ein Schema zur Darstellung von Datentypen und Operationen und richten Sie den Server mit ASP.NET Core ein.

Wie fragt man eine GraphQL-API mit einem C#-Client ab?

Verwenden Sie das GraphQL.Client NuGet-Paket, um einen GraphQLHttpClient mit dem API-Endpunkt-URI einzurichten. Definieren Sie Ihre Abfrage und senden Sie sie mit der Methode SendQueryAsync.

Kann ich eine URL in ein PDF in C# konvertieren?

Ja, Sie können eine URL in ein PDF in C# mit dem ChromePdfRenderer von IronPDF konvertieren. Es ermöglicht Ihnen, HTML-Inhalte direkt von URLs in ein PDF-Dokument zu rendern.

Warum IronPDF in Verbindung mit GraphQL zur PDF-Erstellung verwenden?

IronPDF kann dynamische HTML-Inhalte, die über GraphQL abgerufen werden, in PDFs konvertieren, was ideal ist für die Erstellung von datengetriebenen Berichten, die aktualisierte und spezifische Datenausgaben erfordern.

Wie erstellt man ein einfaches GraphQL-Schema in C#?

Um ein einfaches GraphQL-Schema in C# zu erstellen, definieren Sie die verfügbaren Datentypen und Operationen mit den Schema-Definitionstools der HotChocolate-Bibliothek. Dazu gehört die Angabe von Feldern und deren Datentypen.

Welche Vorteile bietet die Verwendung von GraphQL mit C# für Webanwendungen?

Die Verwendung von GraphQL mit C# bietet Flexibilität und Leistungsverbesserungen, erlaubt effiziente Datenabfragen und -manipulationen, was für den Aufbau moderner Webanwendungen unerlässlich ist.

Wie installiert man IronPDF zur Verwendung in einem C#-Projekt?

Installieren Sie IronPDF für ein C#-Projekt mit dem NuGet-Paketmanager mit dem Befehl: Install-Package IronPdf. Dies ermöglicht Ihnen den Zugriff auf seine PDF-Erstellungs- und Bearbeitungsmöglichkeiten.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen