.NET ヘルプ

Swashbuckle ASP .NET Core(開発者向けの動作説明)

更新済み 1月 27, 2024
共有:

イントロダクション

SwashbuckleはC# .NETコアです。 NuGet 開発されたRESTful Web APIを自動的にドキュメント化するのを助けるパッケージ。 このブログでは、Swashbuckle ASP.NET Coreを探求していきます。 IronPDF ASP.NET Core Web APIの最新アプリケーション開発を可能にするNuGetパッケージ。 一緒に使用することで、最小限のコードで多くの機能を実現できます。

APIドキュメントページは、Web APIプロジェクトから生成されたswagger.jsonを使用するswagger UIツールで表示されます。 生成されたJSONドキュメントはオープンAPI標準に従います。 SwashbuckleはNuGetパッケージとして利用可能です。 Swashbuckle.AspNetCore インストールおよび構成されると、Swagger JSONを自動的に公開します。 スワッガーUIツールは、APIに記述されたXMLコメントから生成されるスワッガーJSONファイルを読み取ります。また、プロジェクト設定ファイルで有効にすることにより、XMLドキュメンテーションファイルを作成することもできます。XMLコメントはXMLドキュメンテーションファイルに変換され、そこからスワッガー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」というWeb APIプロジェクトを作成し、パッケージマネージャーコンソールから.NET Core Web APIプロジェクトにswashbuckleパッケージをインストールします。

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#

TODOリスト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標準をサポートする他のツールやサービスで使用できます。

スワッガーのJSONファイルは、Web APIアプリケーションのベースURLから「/swagger/v1/swagger.json」で利用可能です。

スワッシュバックル ASP .NET コア(開発者向けの動作方法):図2 - スワッガー JSON ファイル。

コードアノテーション

開発者は、XMLコメントと属性を使用して、そのプログラムのドキュメントを作成できます。 ASP.NET スワッガー ドキュメントのための追加情報を提供するコアコントローラ。 以下を翻訳してください:

生成された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で、2番目のパラメータは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#

このオプションは、Swagger ドキュメントをバージョン2.0形式でシリアライズするかどうかを指定します (True) または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 ライブラリ アイアンソフトウェア PDFドキュメントの読み取りと生成をサポートします。 それは、スタイル情報を含むフォーマット済みドキュメントを簡単にPDFに変換することができます。 IronPDFはHTMLコンテンツから簡単にPDFを生成することができます。 URLからHTMLコンテンツをダウンロードし、その後PDFを生成することができます。

インストール

IronPDF インストール方法 NuGetパッケージ マネージャーまたは使用している ビジュアルスタジオ パッケージ マネージャー コンソール。

パッケージ マネージャー コンソールで、次のコマンドを入力します:

Install-Package IronPdf

Visual Studio を使用して

Swashbuckle ASP .NET Core (スワッシュバックル 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 (スワッシュバックル 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#

開発者が登録すると試用ライセンスが利用可能です これ はい、試用ライセンスにはクレジットカードは必要ありません。 メールアドレスを提供し、無料トライアルに登録できます。

結論

スワッシュバックル. アイアンPDFは、適切なドキュメントも提供しています はじめに、およびさまざまな コード例.

また、その他のソフトウェア製品もご覧いただけます アイアンソフトウェア これにより、コーディングスキルを向上させ、最新のアプリケーション要件を満たすことができます。

< 以前
C# ストップウォッチ(開発者向けの動作方法)
次へ >
NPlot C#(開発者向けの仕組み) | IronPDF

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >