在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
Swashbuckle 是 C# .NET CoreNuGet幫助自動記錄所開發的 RESTful Web API 的套件。 在此博客中,我們將探討 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 工具會讀取來自 API 所寫 XML 註解所產生的 swagger JSON 文件。此外,可以透過在專案設定檔中啟用來建立 XML 文件。XML 註解會轉換為 XML 文件,然後從中產生 swagger JSON。 接著,swagger 中介軟體會讀取 JSON 並公開 swagger JSON 端點。
讓我們開始 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
在這裡,我們正在創建一個名為 "SwashbuckleDemo" 的網頁 API 專案,然後從套件管理員控制台中安裝 swashbuckle 套件到 .NET Core Web API 專案。
在 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
還要為待辦清單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)
可以像下面這樣添加控制器:
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
上述代碼可在GitHub - Swashbuckle 演示.
Swagger UI 可在 Web API 應用程式的基本 URL 下的「/swagger/index.html」取得。 它列出程式碼中的所有 REST API。 Swagger 生成器讀取 JSON 文件並填充 UI。
Swashbuckle.AspNetCore 自動生成 Swagger JSON 檔案,該檔案包含有關 API 結構的信息,包括端點、請求和回應類型等詳細內容。 此 JSON 文件可被支持 Swagger/OpenAPI 標準的其他工具和服務使用。
swagger JSON 檔案可從網路 API 應用程式的基底 URL 的 "/swagger/v1/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
Swashbuckle.AspNetCore 提供多種配置選項來自訂 Swagger 文件的生成方式。 開發人員可以控制哪些 API 被記錄,配置命名約定,並調整其他設定。
以下是由 Swashbuckle.AspNetCore 提供的一些主要配置選項:
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"
})
此行指定了 Swagger 文檔版本,並包括 API 的標題和版本等元數據。
c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(xmlPath)
此選項允許您從程式碼中包含 XML 註釋,以在 Swagger 文件中提供其他資訊。 xmlPath 變數應指向您的 XML 註解文件的位置。
c.DescribeAllParametersInCamelCase();
c.DescribeAllParametersInCamelCase();
c.DescribeAllParametersInCamelCase()
此選項配置Swagger生成器以使用小駝峰命名法作為參數名稱。
c.OperationFilter<CustomOperationFilter>();
c.OperationFilter<CustomOperationFilter>();
c.OperationFilter(Of CustomOperationFilter)()
您可以註冊自定義操作過濾器以修改特定操作的 Swagger 文檔。 CustomOperationFilter 是一個實作 IOperationFilter 的類別。
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")
此行配置 Swagger UI 以顯示文件。 第一個參數是 Swagger JSON 文件的 URL,第二個參數是 API 版本的易讀名稱。
c.RoutePrefix = "swagger";
c.RoutePrefix = "swagger";
c.RoutePrefix = "swagger"
您可以設定 Swagger UI 的路徑前綴。 在此範例中,Swagger UI將可在 /swagger 找到。
c.DocExpansion(DocExpansion.None);
c.DocExpansion(DocExpansion.None);
c.DocExpansion(DocExpansion.None)
此選項控制 Swagger UI 如何顯示 API 文件。 DocExpansion.None 預設會折疊所有操作。
c.SerializeAsV2 = true;
c.SerializeAsV2 = true;
c.SerializeAsV2 = True
此選項指定是否以2.0版本格式序列化Swagger文件(真)或者 3.0 格式(錯誤). 如果您想使用 Swagger 2.0,請將其設為 true。
c.DisplayOperationId();
c.DisplayOperationId();
c.DisplayOperationId()
此選項在Swagger UI中顯示操作ID,這對於調試和理解您的API結構非常有用。
c.OAuthClientId("swagger-ui");
c.OAuthClientId("swagger-ui");
c.OAuthClientId("swagger-ui")
如果您的 API 使用 OAuth 驗證,您可以為 Swagger UI 配置 OAuth 客戶端 ID。
這只是一些可用配置選項的例子。 Swashbuckle.AspNetCore 庫具有高度的可自訂性,你可以通過組合各種選項和篩選器來調整 Swagger 文件以滿足你的特定需求。 請隨時參閱官方文件或您開發環境中的 IntelliSense,以獲取有關可用選項的最新和全面的信息。
IronPDF 產品概述是來自 的 C# PDF 庫Iron Software 網站用於閱讀和生成 PDF 文件的工具。 它可以輕鬆將含有樣式資訊的格式化文件轉換為PDF。 IronPDF 可以輕鬆從 HTML 內容生成 PDF。 它可以從 URL 下載 HTML 內容,然後生成 PDF。
通過 NuGet 安裝 IronPDF可以使用NuGet 包管理器詳細資訊或使用Visual Studio 安裝指南套件管理器主控台。
在套件管理器控制台中,輸入指令:
Install-Package IronPdf
使用 Visual Studio
現在,讓我們修改應用程式以新增將網站內容下載為 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
我們在這裡使用天氣數據生成一個HTML字串,然後這個字串被用來生成PDF文件。
PDF 報告如下所示:
整個程式碼可以在 GitHub 上找到 -Swashbuckle Demo 原始碼.
該文件在試用許可證上有一個小型浮水印,可以透過使用有效許可證移除。
要讓上述代碼運行,需要許可證密鑰。 此金鑰必須放在 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"
開發人員可以在註冊後獲得試用許可證IronPDF試用註冊. 試用許可證不需要信用卡。 您可以提供電子郵件地址並註冊免費試用。
瞭解 Swashbuckle 和 IronPDF 可讓您在 ASP.NET Core 應用程式中有效整合 API 文件和 PDF 生成功能。 IronPDF 也提供全面的文件以便入門以及各種PDF 生成的程式碼範例.
此外,您可以探索 Iron Software 的相關軟體產品這將幫助您提高編碼技能並達到現代應用程式的要求。