.NET 幫助

Swashbuckle ASP .NET Core(它如何為開發人員工作)

發佈 2024年1月27日
分享:

介紹

Swashbuckle 是一個 C# .NET core NuGet 可以自動記錄開發的RESTful Web APIs的套件。在這篇博客中,我們將探討Swashbuckle ASP.NET core並 IronPDF NuGet 套件,將啟用現代 ASP.NET Core Web API 應用程式開發。它們共同啟用許多功能,這些功能可以使用最少量的代碼來實現。

API 文件頁面使用 swagger UI 工具顯示,該工具使用從 web API 專案生成的 swagger.json。生成的 JSON 文檔遵循開放 API 標準。Swashbuckle 可作為 NuGet 套件使用。 Swashbuckle.AspNetCore 安裝和配置後,將自動暴露 swagger JSON。swagger UI 工具會讀取由 APIs 上的 XML 註釋所生成的 swagger JSON 文件。此外,可以通過在專案設定文件中啟用來建立 XML 文檔文件。XML 註釋被轉換成 XML 文檔文件,從中生成 swagger JSON。然後 swagger 中介軟體讀取 JSON 並暴露 swagger JSON 端點。

在 .NET Core Web API 專案中的實作

讓我們從 Web API 專案開始

dotnet new webapi -n SwashbuckleDemo
cd Swashbuckle
dotnet build
dotnet add package --version 6.5.0 Swashbuckle.AspNetCore
dotnet build
dotnet new webapi -n SwashbuckleDemo
cd Swashbuckle
dotnet build
dotnet add package --version 6.5.0 Swashbuckle.AspNetCore
dotnet build
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet New webapi -n SwashbuckleDemo cd Swashbuckle dotnet build dotnet add package --version 6.5.0 Swashbuckle.AspNetCore dotnet build
VB   C#

在這裡,我們正在創建一個名為 "SwashbuckleDemo" 的網頁 API 專案,然後從套件管理員控制台中安裝 swashbuckle 套件到 .NET Core Web API 專案。

配置 Swagger 中介軟體

在 Startup.cs 文件中配置 Swagger 服務。

public void ConfigureServices(IServiceCollection services)
{
    // Other service configurations...
    // swagger ui components 
    // Register the Swagger generator
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
        // Optionally, include XML comments for additional information
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath);
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Other app configurations...
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();
    // Enable static file middleware to serve Swagger UI (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });
}
public void ConfigureServices(IServiceCollection services)
{
    // Other service configurations...
    // swagger ui components 
    // Register the Swagger generator
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
        // Optionally, include XML comments for additional information
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath);
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Other app configurations...
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();
    // Enable static file middleware to serve Swagger UI (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	' Other service configurations...
	' swagger ui components 
	' Register the Swagger generator
	services.AddSwaggerGen(Sub(c)
		c.SwaggerDoc("v1", New OpenApiInfo With {
			.Title = "My API",
			.Version = "v1"
		})
		' Optionally, include XML comments for additional information
		Dim xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml"
		Dim xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile)
		c.IncludeXmlComments(xmlPath)
	End Sub)
End Sub
Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IHostingEnvironment)
	' Other app configurations...
	' Enable middleware to serve generated Swagger as a JSON endpoint.
	app.UseSwagger()
	' Enable static file middleware to serve Swagger UI (HTML, JS, CSS, etc.),
	' specifying the Swagger JSON endpoint.
	app.UseSwaggerUI(Sub(c)
		c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1")
	End Sub)
End Sub
VB   C#

還要為待辦清單API添加一個控制器

app.MapGet("/", () => "SwashbuckleDemo!");
app.MapGet("/todoitems", async (TodoDb db) =>
    await db.Todos.ToListAsync());
app.MapGet("/todoitems/complete", async (TodoDb db) =>
    await db.Todos.Where(t => t.IsComplete).ToListAsync());
app.MapGet("/todoitems/{id}", async (int id, TodoDb db) =>
    await db.Todos.FindAsync(id)
        is Todo todo
        ? Results.Ok(todo)
        : Results.NotFound());
app.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
{
    db.Todos.Add(todo);
    await db.SaveChangesAsync();
    return Results.Created($"/todoitems/{todo.Id}", todo);
});
app.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) =>
{
    var todo = await db.Todos.FindAsync(id);
    if (todo is null) return Results.NotFound();
    todo.Name = inputTodo.Name;
    todo.IsComplete = inputTodo.IsComplete;
    await db.SaveChangesAsync();
    return Results.NoContent();
});
app.MapDelete("/todoitems/{id}", async (int id, TodoDb db) =>
{
    if (await db.Todos.FindAsync(id) is Todo todo)
    {
        db.Todos.Remove(todo);
        await db.SaveChangesAsync();
        return Results.Ok(todo);
    }
    return Results.NotFound();
});
app.MapGet("/", () => "SwashbuckleDemo!");
app.MapGet("/todoitems", async (TodoDb db) =>
    await db.Todos.ToListAsync());
app.MapGet("/todoitems/complete", async (TodoDb db) =>
    await db.Todos.Where(t => t.IsComplete).ToListAsync());
app.MapGet("/todoitems/{id}", async (int id, TodoDb db) =>
    await db.Todos.FindAsync(id)
        is Todo todo
        ? Results.Ok(todo)
        : Results.NotFound());
app.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
{
    db.Todos.Add(todo);
    await db.SaveChangesAsync();
    return Results.Created($"/todoitems/{todo.Id}", todo);
});
app.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) =>
{
    var todo = await db.Todos.FindAsync(id);
    if (todo is null) return Results.NotFound();
    todo.Name = inputTodo.Name;
    todo.IsComplete = inputTodo.IsComplete;
    await db.SaveChangesAsync();
    return Results.NoContent();
});
app.MapDelete("/todoitems/{id}", async (int id, TodoDb db) =>
{
    if (await db.Todos.FindAsync(id) is Todo todo)
    {
        db.Todos.Remove(todo);
        await db.SaveChangesAsync();
        return Results.Ok(todo);
    }
    return Results.NotFound();
});
app.MapGet("/", Function() "SwashbuckleDemo!")
app.MapGet("/todoitems", Async Function(db As TodoDb) Await db.Todos.ToListAsync())
app.MapGet("/todoitems/complete", Async Function(db As TodoDb) Await db.Todos.Where(Function(t) t.IsComplete).ToListAsync())
Dim tempVar As Boolean = TypeOf db.Todos.FindAsync(id) Is Todo
Dim todo As Todo = If(tempVar, CType(db.Todos.FindAsync(id), Todo), Nothing)
app.MapGet("/todoitems/{id}", Async Function(id As Integer, db As TodoDb)If(Await tempVar, Results.Ok(todo), Results.NotFound()))
app.MapPost("/todoitems", Async Function(todo As Todo, db As TodoDb)
	db.Todos.Add(todo)
	Await db.SaveChangesAsync()
	Return Results.Created($"/todoitems/{todo.Id}", todo)
End Function)
app.MapPut("/todoitems/{id}", Async Function(id As Integer, inputTodo As Todo, db As TodoDb)
	Dim todo = Await db.Todos.FindAsync(id)
	If todo Is Nothing Then
		Return Results.NotFound()
	End If
	todo.Name = inputTodo.Name
	todo.IsComplete = inputTodo.IsComplete
	Await db.SaveChangesAsync()
	Return Results.NoContent()
End Function)
app.MapDelete("/todoitems/{id}", Async Function(id As Integer, db As TodoDb)
	Dim tempVar2 As Boolean = TypeOf db.Todos.FindAsync(id) Is Todo
	Dim todo As Todo = If(tempVar2, CType(db.Todos.FindAsync(id), Todo), Nothing)
	If Await tempVar2 Then
		db.Todos.Remove(todo)
		Await db.SaveChangesAsync()
		Return Results.Ok(todo)
	End If
	Return Results.NotFound()
End Function)
VB   C#

可以像下面這樣添加控制器:

using Microsoft.AspNetCore.Mvc;
namespace RestFullMinimalApi.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;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    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 RestFullMinimalApi.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;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    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 RestFullMinimalApi.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
		''' <summary>
		''' Retrieves WeatherForecast
		''' </summary>
		''' <remarks>Awesomeness!</remarks>
		''' <response code="200">Retrieved</response>
		''' <response code="404">Not found</response>
		''' <response code="500">Oops! Can't lookup your request right now</response>
		<HttpGet(Name := "GetWeatherForecast")>
		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
VB   C#

上述代碼可在 GitHub.

Swashbuckle 提供以下功能

Swagger UI 工具

Swashbuckle ASP .NET Core(對開發人員的作用):圖1 - Swagger UI 工具

Swagger UI 可從 Web API 應用程式的基底 URL 的 "/swagger/index.html" 存取。它列出了程式碼中的所有 REST API。swagger 生成器會讀取 JSON 文件並填充 UI。

Swagger JSON

Swashbuckle.AspNetCore 自動生成 Swagger JSON 文件,該文件包含有關 API 結構的信息,包括端點、請求和響應類型等細節。這個 JSON 文件可以被支持 Swagger/OpenAPI 標準的其他工具和服務使用。

Swagger JSON 文件可以通過 web API 應用程序的基礎 URL "/swagger/v1/swagger.json" 獲取。

Swashbuckle ASP .NET Core(開發人員如何使用):圖 2 - swagger JSON 文件。

代碼註解

開發人員可以在他們的代碼中使用 XML 註解和屬性 ASP.NET 核心控制器提供有關Swagger文檔的額外信息。這包括描述、示例和其他增強生成的Swagger文檔的元數據。

[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;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    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();
    }
}
[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;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    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();
    }
}
<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
	''' <summary>
	''' Retrieves WeatherForecast
	''' </summary>
	''' <remarks>Awesomeness!</remarks>
	''' <response code="200">Retrieved</response>
	''' <response code="404">Not found</response>
	''' <response code="500">Oops! Can't lookup your request right now</response>
	<HttpGet(Name := "GetWeatherForecast")>
	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
VB   C#

配置選項

Swashbuckle.AspNetCore 提供了各種配置選項,以自定義生成 Swagger 文檔的方式。開發者可以控制要記錄的 API、配置命名約定以及調整其他設置。

以下是 Swashbuckle.AspNetCore 提供的一些主要配置選項:

SwaggerGen 選項

c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.SwaggerDoc("v1", New OpenApiInfo With {
	.Title = "My API",
	.Version = "v1"
})
VB   C#

此行指定了 Swagger 文檔版本,並包括 API 的標題和版本等元數據。

c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(xmlPath)
VB   C#

此選項允許您包含來自代碼的 XML 注釋,以提供額外信息於 Swagger 文件中。xmlPath 變量應指向您的 XML 注釋文件的位置。

c.DescribeAllParametersInCamelCase();
c.DescribeAllParametersInCamelCase();
c.DescribeAllParametersInCamelCase()
VB   C#

此選項配置Swagger生成器使用駝峰命名法作為參數名稱。

c.OperationFilter<CustomOperationFilter>();
c.OperationFilter<CustomOperationFilter>();
c.OperationFilter(Of CustomOperationFilter)()
VB   C#

您可以註冊自定義操作過濾器,以修改特定操作的Swagger文檔。CustomOperationFilter是一個實現IOperationFilter的類別。

Swagger UI 選項

c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1")
VB   C#

此行配置了 Swagger UI 以顯示文件。第一個參數是 Swagger JSON 檔案的 URL,第二個參數是 API 版本的易讀名稱。

c.RoutePrefix = "swagger";
c.RoutePrefix = "swagger";
c.RoutePrefix = "swagger"
VB   C#

您可以設定 Swagger UI 的路由前綴。在此範例中,Swagger UI 將可在 /swagger 上使用。

c.DocExpansion(DocExpansion.None);
c.DocExpansion(DocExpansion.None);
c.DocExpansion(DocExpansion.None)
VB   C#

此選項控制 Swagger UI 如何顯示 API 文件。DocExpansion.None 預設將所有操作折疊。

SwaggerOptions

c.SerializeAsV2 = true;
c.SerializeAsV2 = true;
c.SerializeAsV2 = True
VB   C#

此選項指定是否以2.0版本格式序列化Swagger文件 (真) 或者 3.0 格式 (錯誤). 如果您要使用 Swagger 2.0,請將其設定為 true。

c.DisplayOperationId();
c.DisplayOperationId();
c.DisplayOperationId()
VB   C#

此選項在Swagger UI中顯示操作ID,這對於調試和理解您的API結構非常有用。

c.OAuthClientId("swagger-ui");
c.OAuthClientId("swagger-ui");
c.OAuthClientId("swagger-ui")
VB   C#

如果您的 API 使用 OAuth 認證,您可以為 Swagger UI 配置 OAuth 客戶端 ID。

這只是可用配置選項的一些示例。Swashbuckle.AspNetCore 庫具有高度可定制性,您可以通過組合各種選項和篩選器來調整 Swagger 文檔以滿足您的特定需求。請始終參考官方文檔或您開發環境中的 IntelliSense,以獲取關於可用選項的最新和最全面的資訊。

介紹 IronPDF

IronPDF 是來自 的 C# PDF 庫 Iron Software 有助於閱讀和生成 PDF 文件。它可以輕鬆地將帶有樣式信息的格式化文檔轉換為 PDF。IronPDF 可以輕鬆地從 HTML 內容生成 PDF。它可以從 URL 下載 HTML 內容,然後生成 PDF。

安裝

IronPDF 可以使用 NuGet 套件 管理員或使用 Visual Studio 封裝管理員主控台。

在封裝管理員主控台中,輸入命令:

Install-Package IronPdf

使用 Visual Studio

Swashbuckle ASP .NET Core(它如何為開發人員運作):圖3 - 在 Visual Studio 中打開你的專案。轉到「工具」菜單,選擇「NuGet 套件管理員」,然後選擇「為方案管理 NuGet 套件」。在 NuGet 套件管理員界面,在「瀏覽」選項卡中搜索「ironpdf」套件。然後選擇並安裝最新版本的 IronPDF。

現在,讓我們修改應用程式,添加將網站內容下載為 PDF 檔的功能。

using Microsoft.AspNetCore.Mvc;
namespace RestFullMinimalApi.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;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    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();
    }
    /// <summary>
    /// Retrieves WeatherForecast as Pdf
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet("download", Name = "DownloadWeatherForecast")]
    public IActionResult GetWeatherExcel()
    {
        var results = 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();
        var html = GetHtml(results);
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(html);
        var fileName = "WeatherReport.pdf";
        PDF.SaveAs(fileName);
        var stream = new FileStream(fileName, FileMode.Open);
        // Save the excel file
        return new FileStreamResult(stream, "application/octet-stream") { FileDownloadName = fileName };
    }
    private static string GetHtml(WeatherForecast [] weatherForecasts)
    {
        string header = $@"
<html>
<head><title>WeatherForecast</title></head>
<body>
<h1>WeatherForecast</h1>
    ";
        var footer = @"
</body>
</html>";
        var htmlContent = header;
        foreach (var weather in weatherForecasts)
        {
            htmlContent += $@"
    <h2>{weather.Date}</h2>
    <p>Summary: {weather.Summary}</p>
    <p>Temperature in Celcius: {weather.TemperatureC}</p>
    <p>Temperature in Farenheit: {weather.TemperatureF}</p>
";
        }
        htmlContent += footer;
        return htmlContent;
    }
}
using Microsoft.AspNetCore.Mvc;
namespace RestFullMinimalApi.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;
    }
    /// <summary>
    /// Retrieves WeatherForecast
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet(Name = "GetWeatherForecast")]
    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();
    }
    /// <summary>
    /// Retrieves WeatherForecast as Pdf
    /// </summary>
    /// <remarks>Awesomeness!</remarks>
    /// <response code="200">Retrieved</response>
    /// <response code="404">Not found</response>
    /// <response code="500">Oops! Can't lookup your request right now</response>
    [HttpGet("download", Name = "DownloadWeatherForecast")]
    public IActionResult GetWeatherExcel()
    {
        var results = 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();
        var html = GetHtml(results);
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(html);
        var fileName = "WeatherReport.pdf";
        PDF.SaveAs(fileName);
        var stream = new FileStream(fileName, FileMode.Open);
        // Save the excel file
        return new FileStreamResult(stream, "application/octet-stream") { FileDownloadName = fileName };
    }
    private static string GetHtml(WeatherForecast [] weatherForecasts)
    {
        string header = $@"
<html>
<head><title>WeatherForecast</title></head>
<body>
<h1>WeatherForecast</h1>
    ";
        var footer = @"
</body>
</html>";
        var htmlContent = header;
        foreach (var weather in weatherForecasts)
        {
            htmlContent += $@"
    <h2>{weather.Date}</h2>
    <p>Summary: {weather.Summary}</p>
    <p>Temperature in Celcius: {weather.TemperatureC}</p>
    <p>Temperature in Farenheit: {weather.TemperatureF}</p>
";
        }
        htmlContent += footer;
        return htmlContent;
    }
}
Imports Microsoft.AspNetCore.Mvc
Namespace RestFullMinimalApi.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
		''' <summary>
		''' Retrieves WeatherForecast
		''' </summary>
		''' <remarks>Awesomeness!</remarks>
		''' <response code="200">Retrieved</response>
		''' <response code="404">Not found</response>
		''' <response code="500">Oops! Can't lookup your request right now</response>
		<HttpGet(Name := "GetWeatherForecast")>
		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
		''' <summary>
		''' Retrieves WeatherForecast as Pdf
		''' </summary>
		''' <remarks>Awesomeness!</remarks>
		''' <response code="200">Retrieved</response>
		''' <response code="404">Not found</response>
		''' <response code="500">Oops! Can't lookup your request right now</response>
		<HttpGet("download", Name := "DownloadWeatherForecast")>
		Public Function GetWeatherExcel() As IActionResult
			Dim results = 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()
			Dim html = GetHtml(results)
			Dim Renderer = New ChromePdfRenderer()
			Dim PDF = Renderer.RenderHtmlAsPdf(html)
			Dim fileName = "WeatherReport.pdf"
			PDF.SaveAs(fileName)
			Dim stream = New FileStream(fileName, FileMode.Open)
			' Save the excel file
			Return New FileStreamResult(stream, "application/octet-stream") With {.FileDownloadName = fileName}
		End Function
		Private Shared Function GetHtml(ByVal weatherForecasts() As WeatherForecast) As String
			Dim header As String = $"
<html>
<head><title>WeatherForecast</title></head>
<body>
<h1>WeatherForecast</h1>
    "
	ignore ignore ignore ignore ignore var footer = "
</body>
</html>"
	ignore ignore var htmlContent = header
			For Each weather In weatherForecasts
				htmlContent += $"
    <h2>{weather.Date}</h2>
    <p>Summary: {weather.Summary}</p>
    <p>Temperature in Celcius: {weather.TemperatureC}</p>
    <p>Temperature in Farenheit: {weather.TemperatureF}</p>
"
	ignore ignore ignore ignore ignore
			Next weather
			htmlContent += footer
			Return htmlContent
		End Function
	End Class
End Namespace
VB   C#

我們在這裡使用天氣數據生成一個HTML字串,然後這個字串被用來生成PDF文件。

HTML 內容

Swashbuckle ASP .NET Core(開發人員如何運作):圖4 - 天氣預報的HTML內容。

PDF 報告顯示如下:

Swashbuckle ASP .NET Core(開發人員如何操作):圖5 - HTML到PDF輸出文件:WeatherReport.pdf

整個程式碼可以在 GitHub 上找到 這裡該文件有一個小的水印,用於試用許可證,可以使用有效的許可證將其刪除。

授權 (免費試用)

要使上述程式碼正常運行,需要一個授權密鑰。該密鑰需放置在 appsettings.json 檔案中。

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
VB   C#

開發人員註冊後可獲得試用許可證 這裡 是的,試用版不需要信用卡。只需提供電子郵件地址並註冊免費試用。

結論

SwashbuckleIronPDF 也提供完善的文件說明 如何開始以及各種 程式碼範例

此外,您還可以探索從 Iron Software 這將幫助您提高編碼技能,並達到現代應用程式的需求。

< 上一頁
C# 計時器(它如何對開發者運作)
下一個 >
NPlot C#(開發人員如何使用)| IronPDF

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >