Przejdź do treści stopki
POMOC .NET

Flurl C# (jak to działa dla programistów)

W przypadku programowania w języku C# wykorzystanie wydajnych bibliotek może znacznie zwiększyć wydajność i możliwości. Dwie biblioteki, które dobrze ze sobą współpracują, to Flurl i IronPDF, które zapewniają programistom potężne narzędzia odpowiednio do tworzenia plików PDF i interakcji z internetowymi interfejsami API.

Flurl oferuje płynną, ekspresyjną składnię, która ułatwia pracę z żądaniami HTTP, interfejsami API i ich punktami końcowymi w języku C#. Wysyłanie żądań HTTP, odpowiadanie na nie oraz zarządzanie parametrami zapytania lub nagłówkami to tylko niektóre z zadań, które ułatwia. Dzięki Flurl programiści mogą szybko i skutecznie zarządzać uwierzytelnianiem, serializować i deserializować JSON oraz korzystać z internetowych interfejsów API — a wszystko to przy pisaniu czytelnego i dobrze zorganizowanego kodu.

Programiści mogą wykorzystać łatwość obsługi i wszechstronność Flurl w połączeniu z IronPDF do tworzenia szczegółowych i gotowych dokumentów PDF poprzez łączenie się z interfejsami API sieci Web, pobieranie danych i łatwą integrację ich z IronPDF. Dzięki tej integracji programiści mogą projektować złożone aplikacje, które poprzez automatyzację tworzenia dokumentów przy użyciu danych w czasie rzeczywistym pobieranych z usług internetowych poprawiają wydajność i komfort użytkowania.

W niniejszym wprowadzeniu przyjrzymy się, jak używać i łączyć Flurl oraz IronPDF w programie napisanym w języku C#, podkreślając ich zalety i potencjał synergii we współczesnym tworzeniu oprogramowania.

Czym jest Flurl C#?

Flurl to solidna i przyjazna dla użytkownika biblioteka C# do zarządzania żądaniami HTTP i komunikacji z internetowymi interfejsami API. Zapewnia płynną, łańcuchową składnię, która poprawia czytelność i łatwość utrzymania kodu oraz zmniejsza złożoność interakcji z interfejsami API RESTful. Dzięki Flurl programiści mogą łatwo tworzyć i wysyłać żądania HTTP, obsługiwać odpowiedzi w łatwy do zrozumienia sposób oraz zarządzać parametrami zapytania, nagłówkami i danymi.

Jedną z najbardziej charakterystycznych cech Flurl jest możliwość dynamicznego zarządzania tworzeniem adresów URL, co ułatwia tworzenie i modyfikowanie adresów URL w zależności od warunków środowiska uruchomieniowego, a także pozwala na wykorzystanie go jako samodzielnego Buildersa do tworzenia adresów URL. Oferuje silne wsparcie dla zarządzania serializacją i deserializacją danych JSON oraz obsługuje popularne funkcje HTTP, takie jak GET, POST, PUT, DELETE itp. Dodatkowo Flurl posiada wbudowaną funkcjonalność do zarządzania danymi formularzy i parametrami zapytań, co sprawia, że można go dostosować do szerokiego zakresu scenariuszy integracji API.

Interfejs płynny

Płynna, łańcuchowa składnia zapewniana przez Flurl poprawia czytelność i łatwość utrzymania kodu. Programiści mogą tworzyć proste i wyraziste żądania HTTP oraz pracować z adresami URL, parametrami zapytania, nagłówkami i danymi.

Obsługa metod HTTP

Obsługiwane są wszystkie standardowe metody HTTP, w tym GET, POST, PUT, DELETE, PATCH, HEAD i OPTIONS. Dzięki takiemu kompleksowemu podejściu do wsparcia programiści mogą realizować różne zadania podczas pracy z interfejsami API sieci Web.

Obsługa parametrów zapytania

Flurl oferuje proste sposoby modyfikowania, dodawania i usuwania parametrów zapytania w adresach URL. Ułatwia to tworzenie dynamicznych adresów URL na podstawie danych wprowadzonych przez użytkownika lub sytuacji w czasie wykonywania.

Obsługa JSON

Obsługa danych JSON jest natywnie obsługiwana przez Flurl. Może z łatwością deserializować odpowiedzi JSON do obiektów C# oraz serializować obiekty do formatu JSON na potrzeby ładunków żądań. Dzięki temu korzystanie z interfejsów API opartych na JSON jest proste i łatwe.

Obsługa danych formularzy i przesyłania wieloczęściowego

Ułatwia to zarządzanie żądaniami wieloczęściowymi i danymi formularzy. Flurl ułatwia programistom dołączanie ładunków typu multipart/form-data lub danych zakodowanych w formularzach do żądań HTTP.

Obsługa błędów i zasady ponawiania prób

Flurl oferuje definiowanie zasad ponawiania prób oraz funkcje obsługi błędów dla wszystkich wywołań HTTP. Definiując unikalną logikę obsługi błędów lub techniki ponawiania prób, programiści mogą zwiększyć odporność i niezawodność wywołań API oraz interakcji. Zapewnia to również ochronę i pomaga programistom zapobiegać błędom anonimowych obiektów w odpowiedziach.

Uwierzytelnianie

Obsługuje kilka popularnych metod uwierzytelniania dla interfejsów API, w tym OAuth, niestandardowe schematy uwierzytelniania, uwierzytelnianie podstawowe oraz klucze API. Zapewnia to bezpieczną komunikację z interfejsami API wymagającymi uwierzytelnienia.

Testing Support

By isolating HTTP-related logic into reusable components with a distinct separation of concerns, Flurl encourages testability. This makes writing unit tests for API interactions simpler, as no real network calls are required to test them.

Configuration Flexibility

It provides configuration flexibility for HTTP clients and request parameters. Developers can change client behaviors, timeouts, error response amounts, headers, and other settings to meet the needs of particular applications or API limitations.

Rozszerzalność

Because of its framework for plugins, Flurl is very extendable. Developers can increase the platform's functionality by building unique extensions or incorporating third-party plugins for more features.

Create and configure Flurl C

Here are the following steps to construct and configure Flurl in a C# project:

Create a New Visual Studio Project

W programie Visual Studio łatwo jest utworzyć projekt konsolowy. To start a Console Application in the Visual Studio environment, follow these simple steps:

Ensure Visual Studio is installed on your computer before attempting to use it.

Rozpocznij nowy projekt

Choose File, Project, and then choose the New option.

Flurl C# (How It Works For Developers): Figure 1 - Click on New option

Either the "Console App" or "Console App (.NET Core)" template can be selected from the list of project template references below.

Please fill out the "Name" form to give your project a name.

Flurl C# (How It Works For Developers): Figure 2 - Provide a name and a location

Choose a place to keep the project.

Kliknięcie przycisku "Utwórz" spowoduje otwarcie projektu aplikacji konsolowej.

Flurl C# (How It Works For Developers): Figure 3 - Click Create

Install Flurl.Http Package

The first step is to install the Flurl.Http package using the NuGet Package Manager Console or NuGet Package Manager in Visual Studio.

Install-Package Flurl.Http

Create a FlurlClient Configuration

Flurl offers the FlurlClient class, which allows you to establish default parameters for every HTTP request that comes using just the URL builder. This optional but helpful step can be accomplished by setting base URLs or default headers.

using Flurl;
using Flurl.Http;

// Configure a FlurlClient instance with base URL and headers
FlurlClient flurlClient = new FlurlClient("https://api.example.com/");
flurlClient.WithHeader("Authorization", "Bearer YourAccessTokenHere");
using Flurl;
using Flurl.Http;

// Configure a FlurlClient instance with base URL and headers
FlurlClient flurlClient = new FlurlClient("https://api.example.com/");
flurlClient.WithHeader("Authorization", "Bearer YourAccessTokenHere");
Imports Flurl
Imports Flurl.Http

' Configure a FlurlClient instance with base URL and headers
Private flurlClient As New FlurlClient("https://api.example.com/")
flurlClient.WithHeader("Authorization", "Bearer YourAccessTokenHere")
$vbLabelText   $csharpLabel

Make HTTP Requests

You may now make HTTP requests using Flurl's fluent URL.

var response = await "http://localhost:5013/users".GetAsync();
Console.WriteLine(response.ToString());

if (response.ResponseMessage.IsSuccessStatusCode)
{
    var result = await response.ResponseMessage.Content.ReadAsStringAsync();
    Console.WriteLine(result);
}
else
{
    Console.WriteLine($"Error: {response.StatusCode}");
}
var response = await "http://localhost:5013/users".GetAsync();
Console.WriteLine(response.ToString());

if (response.ResponseMessage.IsSuccessStatusCode)
{
    var result = await response.ResponseMessage.Content.ReadAsStringAsync();
    Console.WriteLine(result);
}
else
{
    Console.WriteLine($"Error: {response.StatusCode}");
}
Dim response = await "http://localhost:5013/users".GetAsync()
Console.WriteLine(response.ToString())

If response.ResponseMessage.IsSuccessStatusCode Then
	Dim result = Await response.ResponseMessage.Content.ReadAsStringAsync()
	Console.WriteLine(result)
Else
	Console.WriteLine($"Error: {response.StatusCode}")
End If
$vbLabelText   $csharpLabel

Flurl C# (How It Works For Developers): Figure 4 - example console output

Handle Responses

To manage response content based on the intended format (JSON, string, etc.), Flurl's HttpResponseMessageExtensions offers extension methods, such as ReceiveJson and ReceiveString.

// Handling JSON response
var responseObject = await "https://api.example.com/resource"
    .WithClient(flurlClient)
    .GetJsonAsync<ResponseType>();
// Assuming ResponseType is a class representing the expected JSON structure
Console.WriteLine($"Response: {responseObject.Property}");
// Handling JSON response
var responseObject = await "https://api.example.com/resource"
    .WithClient(flurlClient)
    .GetJsonAsync<ResponseType>();
// Assuming ResponseType is a class representing the expected JSON structure
Console.WriteLine($"Response: {responseObject.Property}");
Imports System
Imports Flurl.Http

' Handling JSON response
Dim responseObject As ResponseType = Await "https://api.example.com/resource" _
    .WithClient(flurlClient) _
    .GetJsonAsync(Of ResponseType)()
' Assuming ResponseType is a class representing the expected JSON structure
Console.WriteLine($"Response: {responseObject.Property}")
$vbLabelText   $csharpLabel

Dodatkowa konfiguracja

  • Query parameters: To add query parameters, use the .SetQueryParams() method. Ensure that each request runs using the same HttpClient instance for efficiency.

  • Timeouts: For example, you can set up timeouts with .WithTimeout(TimeSpan.FromSeconds(30)).

  • Error Handling: To handle particular error scenarios, use .OnError().

Pierwsze kroki

When you need to retrieve data from a remote API and create PDF documents using that data, integrating Flurl with IronPDF in a C# project can be helpful. To get you started with Flurl and IronPDF, follow these steps:

What is IronPDF?

A feature-rich .NET library named IronPDF is available in C# programs to create, read, and modify PDF documents. With the help of this tool, developers can quickly generate print-ready, high-quality PDFs from HTML, CSS, and JavaScript content. Some essential capabilities include the capacity to watermark, make headers and footers, split and combine PDFs, and convert HTML to PDF. IronPDF supports the .NET Framework and .NET Core, making it useful for various applications.

Because PDFs are simple to integrate and have a wealth of detailed documentation, developers may easily employ them in their applications. IronPDF ensures that the generated PDFs closely resemble the source HTML content by efficiently handling complicated layouts and styling.

IronPDF makes it super simple to convert webpages, URLs, and HTML into high-quality PDFs that look exactly like the original content. It's perfect for creating PDFs of online reports, invoices, and more. If you've been looking for a way to turn HTML to PDF, IronPDF has you covered!

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

Flurl C# (How It Works For Developers): Figure 5 - IronPDF: The C# PDF Library

Funkcje IronPDF

Generowanie plików PDF z HTML

Konwertuj JavaScript, HTML i CSS do formatu PDF. It supports media queries and responsive design, two contemporary web standards. It is useful for dynamically decorating PDF reports, invoices, and documents with HTML and CSS.

Edycja plików PDF

Text, photos, and other content can be added to preexisting PDFs. Text and pictures can be removed from PDF files. Numerous PDFs can be combined into one file. PDF files can be divided into multiple separate papers. Watermarks, annotations, headers, and footers can be included.

Konwersja plików PDF

Convert several file kinds, including Word, Excel, and picture files, to PDF format. PDF to image conversion (PNG, JPEG, etc.).

Wydajność i niezawodność

High performance and dependability are desired design qualities in industrial settings as they can manage extensive document collections effectively.

Zainstaluj IronPDF

To gain the tools you need to work with PDFs in .NET projects, install the IronPDF package.

Install-Package IronPdf

Fetch Data Using Flurl to generate a PDF

To make HTTP queries and get data from your API, use Flurl's fluent API. This is an instance of retrieving JSON data:

using Flurl;
using Flurl.Http;
using IronPdf;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        try
        {
            var response = await "http://localhost:5013/users/1".GetJsonAsync<User>();
            var id = response?.Id;
            var name = response?.Name;
            Console.WriteLine($"Data fetched successfully: {name}");

            // Generate PDF using IronPDF
            var renderer = new ChromePdfRenderer();
            string htmlTemplate = $@"
                <html>
                <body>
                    <h1>{id}</h1>
                    <p>{name}</p>
                </body>
                </html>";

            // Generate PDF document from HTML template
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlTemplate);

            // Save or stream the PDF document
            pdfDocument.SaveAs(@"document.pdf");
            Console.WriteLine("PDF document generated successfully.");
        }
        catch (FlurlHttpException ex)
        {
            Console.WriteLine($"HTTP Error: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

// Example model class for JSON deserialization
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}
using Flurl;
using Flurl.Http;
using IronPdf;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        try
        {
            var response = await "http://localhost:5013/users/1".GetJsonAsync<User>();
            var id = response?.Id;
            var name = response?.Name;
            Console.WriteLine($"Data fetched successfully: {name}");

            // Generate PDF using IronPDF
            var renderer = new ChromePdfRenderer();
            string htmlTemplate = $@"
                <html>
                <body>
                    <h1>{id}</h1>
                    <p>{name}</p>
                </body>
                </html>";

            // Generate PDF document from HTML template
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlTemplate);

            // Save or stream the PDF document
            pdfDocument.SaveAs(@"document.pdf");
            Console.WriteLine("PDF document generated successfully.");
        }
        catch (FlurlHttpException ex)
        {
            Console.WriteLine($"HTTP Error: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

// Example model class for JSON deserialization
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Imports Flurl
Imports Flurl.Http
Imports IronPdf
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		Try
			Dim response = await "http://localhost:5013/users/1".GetJsonAsync(Of User)()
			Dim id = response?.Id
			Dim name = response?.Name
			Console.WriteLine($"Data fetched successfully: {name}")

			' Generate PDF using IronPDF
			Dim renderer = New ChromePdfRenderer()
			Dim htmlTemplate As String = $"
                <html>
                <body>
                    <h1>{id}</h1>
                    <p>{name}</p>
                </body>
                </html>"

			' Generate PDF document from HTML template
			Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlTemplate)

			' Save or stream the PDF document
			pdfDocument.SaveAs("document.pdf")
			Console.WriteLine("PDF document generated successfully.")
		Catch ex As FlurlHttpException
			Console.WriteLine($"HTTP Error: {ex.Message}")
		Catch ex As Exception
			Console.WriteLine($"Error: {ex.Message}")
		End Try
	End Function
End Class

' Example model class for JSON deserialization
Public Class User
	Public Property Id() As Integer
	Public Property Name() As String
End Class
$vbLabelText   $csharpLabel

In this example, Flurl's .GetJsonAsync() function is used to send a GET request and fetch JSON data. Replace User with your model class, which represents the API response structure, and "URL" with your actual API endpoint. An HTML template (htmlTemplate) can be rendered into a PDF document using IronPDF's ChromePdfRenderer class. Here, the title and body data retrieved from the API are used to dynamically construct the HTML template. The created PDF document (pdfDocument) is saved to the specified location ("document.pdf") on the file system. Modify the path as needed.

Flurl C# (How It Works For Developers): Figure 6 - Example Console output

Provide robust error handling for problems like network faults (FlurlHttpException) or general exceptions (Exception) during data fetching or PDF production. You can change the page size, margins, headers, footers, and other PDF settings using IronPDF. For more advanced customization possibilities, see IronPDF's manner manual. When sending HTTP queries to APIs, ensure sensitive data and access tokens are handled securely. Use the proper authentication methods that your API requires.

Wnioski

In summary, combining IronPDF for PDF generation with Flurl for API interaction in a C# application offers a potent combination for dynamically retrieving data and producing high-quality PDF documents. With its fluid API, the Flurl library streamlines HTTP requests and provides flexibility and user-friendliness when retrieving data from distant endpoints. In addition, IronPDF facilitates the easy translation of HTML material into PDF format, offering adjustable features such as headers, margins, and page size.

When implementing this integration, it's also important to consider speed optimization, data security, and error handling. By following best practices and utilizing the advantages of both Flurl and IronPDF, developers may create dependable and scalable solutions that successfully satisfy the requirements of contemporary apps.

IronPDF and Iron Software's Suite offer additional online apps and capabilities and more efficient development by combining Iron Software's highly flexible systems and suite with its core support.

If license alternatives are clear and specific to the project's needs, developers are better able to determine which model is ideal and best practice. These benefits allow developers to manage a range of issues in a clear, compelling, and effortlessly integrated way.

Często Zadawane Pytania

Jak mogę użyć Flurl do pobierania danych z API w języku C#?

Flurl zapewnia płynny interfejs API do wysyłania żądań HTTP, ułatwiając pobieranie danych z API. Można używać metod takich jak GetAsync do pobierania danych i obsługi odpowiedzi bezpośrednio w języku C#.

Jaka jest zaleta korzystania z płynnej składni Flurl w języku C#?

Płynna składnia Flurl poprawia czytelność i łatwość utrzymania kodu, umożliwiając programistom płynne łączenie wywołań metod, co upraszcza proces tworzenia i wysyłania żądań HTTP.

W jaki sposób Flurl radzi sobie z uwierzytelnianiem podczas wysyłania żądań HTTP?

Flurl obsługuje różne metody uwierzytelniania, w tym OAuth i klucze API, umożliwiając bezpieczne interakcje z API poprzez dołączanie danych uwierzytelniających do żądań HTTP.

W jaki sposób Flurl może uprościć obsługę błędów w żądaniach API?

Flurl zapewnia solidne funkcje obsługi błędów i zasady ponawiania prób, umożliwiając programistom wdrażanie niestandardowej logiki obsługi błędów i mechanizmów ponawiania prób w celu zapewnienia niezawodnej interakcji z API w ich aplikacjach.

Jak przekonwertować HTML na PDF w języku C#?

Możesz użyć IronPDF do konwersji treści HTML na pliki PDF w języku C#. IronPDF obsługuje konwersję HTML, CSS i JavaScript na wysokiej jakości pliki PDF, umożliwiając jednocześnie korzystanie z dodatkowych funkcji, takich jak nagłówki, stopki i znaki wodne.

Czy Flurl i bibliotekę do generowania plików PDF można zintegrować z aplikacją napisana w języku C#?

Tak, Flurl może służyć do pobierania danych z interfejsów API, które następnie można przetwarzać i konwertować na dokumenty PDF przy użyciu biblioteki takiej jak IronPDF. Ta integracja pozwala na dynamiczne generowanie plików PDF na podstawie danych w czasie rzeczywistym.

Jakie są zalety korzystania z Flurl do żądań HTTP w języku C#?

Flurl poprawia wydajność i przejrzystość kodu podczas zarządzania żądaniami HTTP, oferując prosty interfejs do obsługi różnych metod HTTP, uwierzytelniania i zarządzania błędami, co czyni go idealnym rozwiązaniem dla nowoczesnych aplikacji opartych na API.

W jaki sposób biblioteka do generowania plików PDF radzi sobie z responsywnym projektowaniem?

IronPDF obsługuje zapytania o media i responsywny projekt, zapewniając, że zawartość HTML jest dokładnie odwzorowana w wynikowym pliku PDF, niezależnie od urządzenia lub rozmiaru ekranu, dla którego została pierwotnie zaprojektowana.

Jacob Mellor, Dyrektor Technologiczny @ Team Iron
Dyrektor ds. technologii

Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczą...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie