Saltar al pie de página
.NET AYUDA

OpenAPI .NET (Cómo Funciona para Desarrolladores)

OpenAPI, formerly known as Swagger, is a specification for building and describing RESTful APIs. It allows developers to define the structure of their APIs in a standardized format, enabling various tools and services to understand and interact with the REST API effectively and provide feedback. In the .NET ecosystem, OpenAPI .NET integration is facilitated through several libraries and tools that make it easier to create, document, and consume APIs.

In this article, we will learn about OpenAPI support specifications and how to create a PDF file using IronPDF and return it as an API call response.

Setting Up OpenAPI in .NET

To get started with the OpenAPI .NET project, you typically use the Swashbuckle library, which generates OpenAPI specification or documentation for your ASP.NET Core APIs.

Step 1: Install Swashbuckle

First, you need to install the Swashbuckle.AspNetCore package via NuGet in Visual Studio. You can do this using the NuGet Package Manager Console:

Install-Package Swashbuckle.AspNetCore

Or by using the .NET CLI:

dotnet add package Swashbuckle.AspNetCore
dotnet add package Swashbuckle.AspNetCore
SHELL

Step 2: Configure Swashbuckle

Next, you need to configure Swashbuckle in your ASP.NET Core project. This involves updating the Program.cs file to add Swagger services and configure the Swagger middleware.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// Configures Swagger/OpenAPI descriptions.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// Configures Swagger/OpenAPI descriptions.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Dim builder = WebApplication.CreateBuilder(args)

' Add services to the container.
builder.Services.AddControllers()
' Configures Swagger/OpenAPI descriptions.
builder.Services.AddEndpointsApiExplorer()
builder.Services.AddSwaggerGen()

Dim app = builder.Build()

' Configure the HTTP request pipeline.
If app.Environment.IsDevelopment() Then
	app.UseSwagger()
	app.UseSwaggerUI()
End If

app.UseHttpsRedirection()
app.UseAuthorization()
app.MapControllers()
app.Run()
$vbLabelText   $csharpLabel

Generating and Viewing API Documentation

Once Swashbuckle is configured, running your application will automatically generate OpenAPI documentation. You can view these OpenAPI descriptions by navigating to the Swagger UI interface.

Using OpenAPI Definitions

OpenAPI definitions are powerful tools that can be used for generating client SDKs, testing APIs, and ensuring consistency across different services. The OpenAPI specification defines a standard, language-agnostic interface to APIs, which allows both humans and computers to understand the capabilities of a service without access to the source code.

Extending OpenAPI with Custom Annotations

Swashbuckle allows you to enhance your OpenAPI documentation with custom annotations. These annotations can be added directly to your controllers and models to provide additional information about the API's behavior and data structures.

Example: Custom Annotations

using Microsoft.AspNetCore.Mvc;

namespace WebApplication8.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        [SwaggerOperation(Summary = "Gets the weather forecast for the next 5 days")]
        [SwaggerResponse(200, "Successfully retrieved weather forecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}
using Microsoft.AspNetCore.Mvc;

namespace WebApplication8.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        [SwaggerOperation(Summary = "Gets the weather forecast for the next 5 days")]
        [SwaggerResponse(200, "Successfully retrieved weather forecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}
Imports Microsoft.AspNetCore.Mvc

Namespace WebApplication8.Controllers
	<ApiController>
	<Route("[controller]")>
	Public Class WeatherForecastController
		Inherits ControllerBase

		Private Shared ReadOnly Summaries() As String = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }

		Private ReadOnly _logger As ILogger(Of WeatherForecastController)

		Public Sub New(ByVal logger As ILogger(Of WeatherForecastController))
			_logger = logger
		End Sub

		<HttpGet(Name := "GetWeatherForecast")>
		<SwaggerOperation(Summary := "Gets the weather forecast for the next 5 days")>
		<SwaggerResponse(200, "Successfully retrieved weather forecast")>
		Public Function [Get]() As IEnumerable(Of WeatherForecast)
			Return Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
				.Date = DateTime.Now.AddDays(index),
				.TemperatureC = Random.Shared.Next(-20, 55),
				.Summary = Summaries(Random.Shared.Next(Summaries.Length))
			}).ToArray()
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

In this example, the SwaggerOperation and SwaggerResponse attributes are used to provide detailed OpenAPI descriptions and response codes for the endpoint.

Output

OpenAPI .NET (How It Works For Developers): Figure 1 - Custom Annotations Output

Click on the Execute button, and you will get the following response.

OpenAPI .NET (How It Works For Developers): Figure 2 - Response Output

IronPDF

IronPDF for ASP.NET is a powerful tool that enables seamless generation and manipulation of PDF documents within ASP.NET applications. With its intuitive API and robust functionality, developers can effortlessly integrate PDF generation into their web projects, offering enhanced document management capabilities to users. Whether it's creating PDFs from scratch, converting HTML content to PDF, or adding dynamic elements like images and text, IronPDF simplifies the process, ensuring efficient and professional document generation.

Steps to install using NuGet Package Manager:

  1. Open your ASP.NET project in Visual Studio and navigate to the "Tools" menu.
  2. Select "NuGet Package Manager" and then click on "Manage NuGet Packages for Solution."
  3. In the "Browse" tab, search for "IronPDF" and select the desired version. Click on "Install" to add the package to your project. IronPDF and its dependencies will be automatically downloaded and integrated, allowing you to start leveraging its functionality in your ASP.NET application seamlessly.

OpenAPI .NET (How It Works For Developers): Figure 3 - IronPDF

Get PDF File in Response to API Call

Add the following code to your controller file, it uses IronPDF to create a PDF file and return it as a response to the API call.

using Microsoft.AspNetCore.Mvc;
using IronPdf;

namespace WebApplication8.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IActionResult GetWeatherForecastPdf()
        {
            var htmlContent = @"
        <html>
        <head>
            <title>Weather Forecast</title>
        </head>
        <body>
            <h1>Weather Forecast</h1>
            <table>
                <tr>
                    <th>Date</th>
                    <th>Temperature (Celsius)</th>
                    <th>Summary</th>
                </tr>";

            var forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            });

            // Iterate over the forecasts and add data to the HTML string
            foreach (var forecast in forecasts)
            {
                htmlContent += $@"
            <tr>
                <td>{forecast.Date.ToShortDateString()}</td>
                <td>{forecast.TemperatureC}</td>
                <td>{forecast.Summary}</td>
            </tr>";
            }

            htmlContent += @"
            </table>
        </body>
        </html>";

            // Convert the HTML string to a PDF using IronPDF
            var renderer = new ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

            // Retrieve the byte array of the generated PDF
            var pdfBytes = pdfDocument.BinaryData;
            // Return the PDF file to the client
            return File(pdfBytes, "application/pdf", "WeatherForecast.pdf");
        }
    }
}
using Microsoft.AspNetCore.Mvc;
using IronPdf;

namespace WebApplication8.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IActionResult GetWeatherForecastPdf()
        {
            var htmlContent = @"
        <html>
        <head>
            <title>Weather Forecast</title>
        </head>
        <body>
            <h1>Weather Forecast</h1>
            <table>
                <tr>
                    <th>Date</th>
                    <th>Temperature (Celsius)</th>
                    <th>Summary</th>
                </tr>";

            var forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            });

            // Iterate over the forecasts and add data to the HTML string
            foreach (var forecast in forecasts)
            {
                htmlContent += $@"
            <tr>
                <td>{forecast.Date.ToShortDateString()}</td>
                <td>{forecast.TemperatureC}</td>
                <td>{forecast.Summary}</td>
            </tr>";
            }

            htmlContent += @"
            </table>
        </body>
        </html>";

            // Convert the HTML string to a PDF using IronPDF
            var renderer = new ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

            // Retrieve the byte array of the generated PDF
            var pdfBytes = pdfDocument.BinaryData;
            // Return the PDF file to the client
            return File(pdfBytes, "application/pdf", "WeatherForecast.pdf");
        }
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports IronPdf

Namespace WebApplication8.Controllers
	<ApiController>
	<Route("[controller]")>
	Public Class WeatherForecastController
		Inherits ControllerBase

		Private Shared ReadOnly Summaries() As String = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }

		Private ReadOnly _logger As ILogger(Of WeatherForecastController)

		Public Sub New(ByVal logger As ILogger(Of WeatherForecastController))
			_logger = logger
		End Sub

		<HttpGet(Name := "GetWeatherForecast")>
		Public Function GetWeatherForecastPdf() As IActionResult
			Dim htmlContent = "
        <html>
        <head>
            <title>Weather Forecast</title>
        </head>
        <body>
            <h1>Weather Forecast</h1>
            <table>
                <tr>
                    <th>Date</th>
                    <th>Temperature (Celsius)</th>
                    <th>Summary</th>
                </tr>"

			Dim forecasts = Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
				.Date = DateTime.Now.AddDays(index),
				.TemperatureC = Random.Shared.Next(-20, 55),
				.Summary = Summaries(Random.Shared.Next(Summaries.Length))
			})

			' Iterate over the forecasts and add data to the HTML string
			For Each forecast In forecasts
				htmlContent &= $"
            <tr>
                <td>{forecast.Date.ToShortDateString()}</td>
                <td>{forecast.TemperatureC}</td>
                <td>{forecast.Summary}</td>
            </tr>"
			Next forecast

			htmlContent &= "
            </table>
        </body>
        </html>"

			' Convert the HTML string to a PDF using IronPDF
			Dim renderer = New ChromePdfRenderer()
			Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

			' Retrieve the byte array of the generated PDF
			Dim pdfBytes = pdfDocument.BinaryData
			' Return the PDF file to the client
			Return File(pdfBytes, "application/pdf", "WeatherForecast.pdf")
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

OpenAPI .NET (How It Works For Developers): Figure 4 - API Output

Download and open the attached PDF file.

OpenAPI .NET (How It Works For Developers): Figure 5 - PDF Output

Conclusion

OpenAPI, formerly known as Swagger, streamlines RESTful API design and documentation in the .NET ecosystem through libraries like Swashbuckle, facilitating automatic API documentation generation for ASP.NET Core projects. Demonstrating the synergy between OpenAPI and IronPDF, we showcased how to utilize IronPDF's capabilities to generate PDF files from HTML content and return them as API responses, enriching the functionality of ASP.NET applications. By embracing OpenAPI standards and leveraging IronPDF's robust features, developers can enhance their API documentation practices and deliver polished, feature-rich applications to users.

For detailed information on IronPDF licensing, please refer to the IronPDF licensing details. Additionally, you can explore our HTML to PDF conversion tutorial for further guidance.

Preguntas Frecuentes

¿Cómo puedo convertir contenido HTML a PDF en una aplicación ASP.NET?

Puede usar IronPDF en una aplicación ASP.NET para convertir contenido HTML a PDF. Al aprovechar las capacidades de IronPDF, puede renderizar cadenas o archivos HTML en documentos PDF, que luego pueden ser servidos como respuestas de API o guardados para fines de gestión de documentos.

¿Cuál es el papel de OpenAPI en el ecosistema .NET?

OpenAPI juega un papel crucial en el ecosistema .NET al proporcionar una forma estandarizada de definir y documentar APIs RESTful. Esta integración a menudo se facilita a través de herramientas como Swashbuckle, que ayuda a generar especificaciones OpenAPI y habilita el consumo fácil de APIs dentro de proyectos ASP.NET Core.

¿Cómo configuro Swagger UI en un proyecto .NET usando Swashbuckle?

Para configurar Swagger UI en un proyecto .NET usando Swashbuckle, instale el paquete Swashbuckle.AspNetCore a través de NuGet. Luego, configure los servicios Swagger en su archivo Program.cs y configure el middleware de Swagger para habilitar la generación automática y el acceso a la documentación de API a través de Swagger UI.

¿Cómo puedo generar SDKs de cliente a partir de definiciones OpenAPI en .NET?

Las definiciones OpenAPI pueden usarse para generar SDKs de cliente, que facilitan el consumo de APIs al abstraer la complejidad de las llamadas se API. En .NET, herramientas como Swashbuckle pueden generar estas definiciones, que luego pueden usarse con herramientas como AutoRest para crear SDKs de cliente en diversos lenguajes de programación.

¿Cuáles son las ventajas de usar anotaciones personalizadas en la documentación OpenAPI?

Las anotaciones personalizadas en la documentación OpenAPI mejoran la claridad y el detalle de las especificaciones de API. En .NET, Swashbuckle le permite usar atributos como SwaggerOperation y SwaggerResponse para agregar descripciones y códigos de respuesta, haciendo la documentación de la API más informativa y fácil de entender para los desarrolladores.

¿Cómo puedo entregar un archivo PDF como respuesta de API en ASP.NET Core?

Puede entregar un archivo PDF como respuesta de API en ASP.NET Core usando IronPDF. Genere el PDF a partir de contenido HTML usando los métodos de renderizado de IronPDF y devuelva el archivo PDF en su acción de controlador API usando IActionResult de ASP.NET Core para enviar el archivo como parte de la respuesta.

¿Qué beneficios trae la combinación de OpenAPI y herramientas de generación de PDF a las aplicaciones ASP.NET?

La combinación de OpenAPI y herramientas de generación de PDF como IronPDF en aplicaciones ASP.NET proporciona una documentación de API integral y mejora la funcionalidad al permitir que las APIs devuelvan documentos PDF profesionales. Esta integración apoya la gestión eficiente de documentos y enriquece las capacidades generales de la aplicación.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más