Altbilgi içeriğine atla
.NET YARDıM

Swashbuckle ASP .NET Core (Geliştiriciler İçin Nasıl Çalışır)

Swashbuckle, RESTful Web API'leri otomatik olarak belgelemeye yardımcı olan bir C# .NET Core NuGet paketidir. Bu blogda, modern ASP.NET Core Web API'lerinin geliştirilmesini sağlayan Swashbuckle ASP.NET Core ve IronPDF Kurulum Talimatları NuGet paketlerini keşfedeceğiz. Birlikte, minimum kod ile elde edilebilecek çeşitli işlevsellikler sunarlar.

API dokümantasyon sayfaları, Web API projesinden üretilen swagger.json dosyasını kullanan Swagger UI aracı kullanılarak görüntülenir. Oluşturulan JSON belgesi Open API standardına uygundur. Swashbuckle, kurulduğunda ve yapılandırıldığında otomatik olarak Swagger JSON'u yayınlayacak Swashbuckle.AspNetCore NuGet paketi olarak mevcuttur. Swagger UI aracı, API'ler üzerinde yazılı XML yorumlarından üretilen Swagger JSON dosyasını okur. Ayrıca, proje ayarları dosyasında etkinleştirilerek bir XML dokümantasyon dosyası oluşturulabilir. XML yorumları bir XML dokümantasyon dosyasına dönüştürülür ve buradan Swagger JSON oluşturulur. Sonra, Swagger ara yazılımı JSON'u okur ve Swagger JSON uç noktalarını yayınlar.

.NET Core Web API projesi Uygulama

Bir Web API projesi ile başlayalım:

dotnet new webapi -n SwashbuckleDemo
cd SwashbuckleDemo
dotnet build
dotnet add package Swashbuckle.AspNetCore --version 6.5.0
dotnet build
dotnet new webapi -n SwashbuckleDemo
cd SwashbuckleDemo
dotnet build
dotnet add package Swashbuckle.AspNetCore --version 6.5.0
dotnet build
SHELL

Burada, "SwashbuckleDemo" adında bir web API projesi oluşturuyoruz ve ardından Paket Yönetici Konsolunu kullanarak .NET Core Web API projesine Swashbuckle paketini yüklüyoruz.

Swagger Ara Yazılımını Yapılandırma

Swagger servislerini Startup.cs dosyasında yapılandırın.

using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Other service configurations...

        // 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 Swagger UI (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });
    }
}
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Other service configurations...

        // 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 Swagger UI (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });
    }
}
Imports System.Reflection
Imports Microsoft.Extensions.DependencyInjection
Imports Microsoft.AspNetCore.Builder

Public Class Startup
	Public Sub ConfigureServices(ByVal services As IServiceCollection)
		' Other service configurations...

		' 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 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
End Class
$vbLabelText   $csharpLabel

Yapılacaklar listesi API'leri için bir denetleyici ekleyin:

using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

// Example to define an entity class
public class Todo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsComplete { get; set; }
}

// Example to define a DbContext class
public class TodoDb : DbContext
{
    public DbSet<Todo> Todos => Set<Todo>();
}

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

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.Run();
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

// Example to define an entity class
public class Todo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsComplete { get; set; }
}

// Example to define a DbContext class
public class TodoDb : DbContext
{
    public DbSet<Todo> Todos => Set<Todo>();
}

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

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.Run();
Imports Microsoft.AspNetCore.Http.HttpResults
Imports Microsoft.AspNetCore.Builder
Imports Microsoft.EntityFrameworkCore
Imports Microsoft.AspNetCore.Mvc
Imports System.Threading.Tasks

' Example to define an entity class
Public Class Todo
	Public Property Id() As Integer
	Public Property Name() As String
	Public Property IsComplete() As Boolean
End Class

' Example to define a DbContext class
Public Class TodoDb
	Inherits DbContext

	Public ReadOnly Property Todos() As DbSet(Of Todo)
		Get
			Return [Set](Of Todo)()
		End Get
	End Property
End Class

Private builder = WebApplication.CreateBuilder(args)
Private app = builder.Build()

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)

app.Run()
$vbLabelText   $csharpLabel

Aşağıdaki gibi bir denetleyici de eklenebilir:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System;
using System.Linq;

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();
        }
    }

    public class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public string Summary { get; set; }
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System;
using System.Linq;

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();
        }
    }

    public class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public string Summary { get; set; }
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.Extensions.Logging
Imports System.Collections.Generic
Imports System
Imports System.Linq

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

	Public Class WeatherForecast
		Public Property [Date]() As DateTime
		Public Property TemperatureC() As Integer
		Public Property Summary() As String
	End Class
End Namespace
$vbLabelText   $csharpLabel

Yukarıdaki kod GitHub - Swashbuckle Demo üzerinde mevcut.

Swashbuckle aşağıdaki özellikleri sunar

Swagger UI aracı

Swashbuckle ASP .NET Core (Geliştirici İçin Nasıl Çalışır): Şekil 1 - Swagger UI aracı

Swagger UI, Web API uygulamasının temel URL'sinden "/swagger/index.html" adresinde mevcuttur. Koddan tüm REST API'lerini listeler. Swagger jeneratörü, JSON dosyasını okur ve kullanıcı arayüzünü doldurur.

Swagger JSON

Swashbuckle.AspNetCore, API yapısı hakkında bilgi içeren ve uç noktalar, istek ve yanıt türleri gibi detayları içeren Swagger JSON dosyasını otomatik olarak oluşturur. Bu JSON dosyası, Swagger/OpenAPI standardını destekleyen diğer araçlar ve servisler tarafından kullanılabilir.

Swagger JSON dosyası, web API uygulamasının temel URL'sinden "/swagger/v1/swagger.json" adresinde mevcuttur.

Swashbuckle ASP .NET Core (Geliştirici İçin Nasıl Çalışır): Şekil 2 - Swagger JSON dosyası.

Kod Açıklamaları

Geliştiriciler, Swagger dokümantasyonu için ek bilgi sağlamak adına ASP.NET Core denetleyicileri içerisinde XML yorumları ve öznitelikler kullanabilirler. Bu, oluşturulan Swagger dokümantasyonunu geliştiren açıklamalar, örnekler ve diğer meta verileri içerir.

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

Yapılandırma Seçenekleri

Swashbuckle.AspNetCore, Swagger dokümantasyonunun nasıl oluşturulacağı konusunda çeşitli yapılandırma seçenekleri sunar. Geliştiriciler, hangi API'lerin belgeleneceğini kontrol edebilir, adlandırma kurallarını yapılandırabilir ve diğer ayarları ayarlayabilir.

Swashbuckle.AspNetCore'un sunduğu bazı önemli yapılandırma seçenekleri şunlardır:

SwaggerGen Seçenekleri

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"
})
$vbLabelText   $csharpLabel

Bu satır, Swagger belge sürümünü belirtir ve API'nizin başlığı ve sürümü gibi meta verileri içerir.

c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(xmlPath)
$vbLabelText   $csharpLabel

Bu seçenek, Swagger dokümantasyonunda ek bilgi sağlamak için kodunuzdan XML yorumlarını içerebilmenizi sağlar. xmlPath değişkeni, XML yorum dosyanızın konumunu işaret etmelidir.

c.DescribeAllParametersInCamelCase();
c.DescribeAllParametersInCamelCase();
c.DescribeAllParametersInCamelCase()
$vbLabelText   $csharpLabel

Bu seçenek, Swagger jeneratörünün parametre adları için camelCase kullanımını yapılandırır.

c.OperationFilter<CustomOperationFilter>();
c.OperationFilter<CustomOperationFilter>();
c.OperationFilter(Of CustomOperationFilter)()
$vbLabelText   $csharpLabel

Özel işletim filtrelerini, belirli işlemler için Swagger dokümantasyonunu değiştirmek üzere kaydedebilirsiniz. CustomOperationFilter, IOperationFilter uygulayan bir sınıftır.

Swagger UI Seçenekleri

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

Bu satır, Swagger UI'nın dokümantasyonu görüntülemesini yapılandırır. İlk parametre, Swagger JSON dosyasının URL'si, ikinci parametre ise bir API sürümü için kullanıcı dostu bir isimdir.

c.RoutePrefix = "swagger";
c.RoutePrefix = "swagger";
c.RoutePrefix = "swagger"
$vbLabelText   $csharpLabel

Swagger UI için rota ön ekini ayarlayabilirsiniz. Bu örnekte, Swagger UI /swagger adresinde mevcut olacaktır.

c.DocExpansion(DocExpansion.None);
c.DocExpansion(DocExpansion.None);
c.DocExpansion(DocExpansion.None)
$vbLabelText   $csharpLabel

Bu seçenek, Swagger UI'nın API dokümantasyonunu nasıl görüntüleyeceğini kontrol eder. DocExpansion.None varsayılan olarak tüm işlemleri daraltır.

SwaggerOptions

c.SerializeAsV2 = true;
c.SerializeAsV2 = true;
c.SerializeAsV2 = True
$vbLabelText   $csharpLabel

Bu seçenek, Swagger belgesini sürüm 2.0 formatında (true) veya 3.0 formatında (false) serileştirme durumunu belirtir. Swagger 2.0 kullanmak istiyorsanız, onu true olarak ayarlayın.

c.DisplayOperationId();
c.DisplayOperationId();
c.DisplayOperationId()
$vbLabelText   $csharpLabel

Bu seçenek, Swagger UI'da operasyon kimliğini görüntüler, bu da API'nizin yapısını anlamanıza ve hata ayıklamanıza yardımcı olabilir.

c.OAuthClientId("swagger-ui");
c.OAuthClientId("swagger-ui");
c.OAuthClientId("swagger-ui")
$vbLabelText   $csharpLabel

API'niz OAuth kimlik doğrulamasını kullanıyorsa, Swagger UI için OAuth istemci kimliğini yapılandırabilirsiniz.

Bunlar mevcut yapılandırma seçeneklerinden sadece birkaç örnektir. Swashbuckle.AspNetCore kütüphanesi son derece özelleştirilebilir ve çeşitli seçenekler ve filtreleri birleştirerek ihtiyaçlarınıza özel bir Swagger belgelenmesi yapabilirsiniz. Kullanılabilir seçeneklerle ilgili en güncel ve kapsamlı bilgi için her zaman resmi dokümantasyona veya geliştirme ortamınızdaki IntelliSense'e başvurun.

IronPDF Tanıtımı

IronPDF Ürün Genel Bakışı, Iron Software Web Sitesi'nden PDF belgelerini okumaya ve oluşturmaya yardımcı olan C# PDF Kütüphanesidir. Biçimlendirilmiş dokümanları stil bilgisi ile PDF'ye kolayca dönüştürebilir. IronPDF, HTML içeriğinden kolaylıkla PDF oluşturabilir. HTML içeriğini bir URL'den indirebilir ve ardından PDF oluşturabilir.

IronPDF, web sayfalarını, URL'leri ve HTML'i PDF'lere dönüştürmek için mükemmel bir araçtır. Çevrimiçi içeriklerin, raporlar ve faturaların PDF'lerini oluşturmak için idealdir ve her web sayfasının PDF sürümlerini kolayca oluşturur.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Kurulum

NuGet üzerinden IronPDF'i yükleyin ve NuGet Paket Yöneticisi Detayları veya Visual Studio Yükleme Kılavuzu paket yöneticisi konsolunu kullanın.

Paket Yöneticisi Konsolu'nda şu komutu girin:

Install-Package IronPdf

Visual Studio Kullanarak

![Swashbuckle ASP .NET Core (Geliştiriciler İçin Nasıl Çalışır): Görsel 3 - Projenizi Visual Studio'da açın. "Araçlar" menüsüne gidin, "NuGet Paket Yöneticisi"ni seçin, ardından "Çözüm İçin NuGet Paketlerini Yönet" seçeneğini seçin. NuGet Paket Yöneticisi arayüzünde, Ara sekmesinde "ironpdf" paketini arayın. Daha sonra en son IronPDF sürümünü seçip yükleyin.

Şimdi, uygulamamızı web sitesi içeriğini PDF dosyası olarak indirme işlevselliği ekleyecek şekilde değiştirelim.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

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 GetWeatherPdf()
        {
            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);
            // Return the PDF file for download
            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 Celsius: {weather.TemperatureC}</p>
    <p>Temperature in Fahrenheit: {weather.TemperatureF}</p>
";
            }
            htmlContent += footer;
            return htmlContent;
        }
    }

    public class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public string Summary { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

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 GetWeatherPdf()
        {
            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);
            // Return the PDF file for download
            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 Celsius: {weather.TemperatureC}</p>
    <p>Temperature in Fahrenheit: {weather.TemperatureF}</p>
";
            }
            htmlContent += footer;
            return htmlContent;
        }
    }

    public class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public string Summary { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.Extensions.Logging
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq

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 GetWeatherPdf() 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)
			' Return the PDF file for download
			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>
"

			Dim footer = "
</body>
</html>"

			Dim htmlContent = header
			For Each weather In weatherForecasts
				htmlContent &= $"
    <h2>{weather.Date}</h2>
    <p>Summary: {weather.Summary}</p>
    <p>Temperature in Celsius: {weather.TemperatureC}</p>
    <p>Temperature in Fahrenheit: {weather.TemperatureF}</p>
"
			Next weather
			htmlContent &= footer
			Return htmlContent
		End Function
	End Class

	Public Class WeatherForecast
		Public Property [Date]() As DateTime
		Public Property TemperatureC() As Integer
		Public Property Summary() As String

		Public ReadOnly Property TemperatureF() As Integer
			Get
				Return 32 + CInt(Math.Truncate(TemperatureC / 0.5556))
			End Get
		End Property
	End Class
End Namespace
$vbLabelText   $csharpLabel

Burada, bir HTML dizesi oluşturmak için hava durumu verilerini kullanıyoruz ve bu daha sonra bir PDF belgesi oluşturmak için kullanılır.

HTML İçeriği

Swashbuckle ASP .NET Core (Geliştirici İçin Nasıl Çalışır): Şekil 4 - Hava Durumu Tahmini için HTML içeriği.

Ve PDF raporu şu şekilde görünür:

Swashbuckle ASP .NET Core (Geliştirici İçin Nasıl Çalışır): Şekil 5 - HTML'den PDF'ye Çıkış dosyası: WeatherReport.pdf

Tüm kod GitHub'da - Swashbuckle Demo Kaynak Kodu olarak bulunabilir.
Belgede deneme lisansları için küçük bir filigran vardır, geçerli bir lisansla kaldırılabilir.

Lisanslama (Ücretsiz Deneme Mevcut)

Yukarıdaki kodun çalışması için lisans anahtarı gereklidir. Bu anahtarı appsettings.json dosyasına yerleştirin.

{
    "IronPdf": {
        "LicenseKey": "your license key"
    }
}

Geliştiriciler için IronPDF Deneme Kaydı ile kayıt yapıldığında bir deneme lisansı mevcuttur. Deneme lisansı için kredi kartı gerekmez. Ücretsiz bir deneme almak için e-posta adresinizle kaydolun.

Sonuç

Swashbuckle ve IronPDF'i anlamak, API dokümantasyonu ve PDF oluşturma yeteneklerini ASP.NET Core uygulamalarınıza etkili bir şekilde entegre etmenizi sağlar. IronPDF ayrıca Başlarken, ve çeşitli PDF Oluşturma İçin Kod Örnekleri ile ilgili kapsamlı dokümantasyon sunar.

Iron Software'dan ilgili yazılım ürünlerini keşfedin kodlama becerilerinizi geliştirmek ve modern uygulama gereksinimlerini karşılamak için.

Sıkça Sorulan Sorular

Swashbuckle'ı ASP.NET Core'da kullanarak RESTful Web API'lerini nasıl belgeleyebilirim?

Swashbuckle, koddaki XML yorumlarından Swagger belgeleri oluşturarak RESTful Web API'lerini belgelemek için kullanılabilir. Swashbuckle.AspNetCore paketini yüklemeniz ve ASP.NET Core projenizin `Startup.cs` dosyasında yapılandırmanız gerekir.

Yeni bir ASP.NET Core Web API projesi için Swashbuckle'ı kurarken hangi adımlar yer alır?

Swashbuckle'ı kurmak için, önce Swashbuckle.AspNetCore NuGet paketini yükleyin. Sonrasında, `ConfigureServices` yöntemine `services.AddSwaggerGen()` ve `Configure` yöntemine `app.UseSwagger()` ve `app.UseSwaggerUI()` ekleyerek `Startup.cs` dosyasında Swagger middleware'ini yapılandırın.

.NET Core uygulamasında HTML içeriğini PDF'ye nasıl dönüştürebilirim?

.NET Core uygulamasında HTML içeriğini PDF'ye IronPDF ile dönüştürebilirsiniz. Bu kütüphane, `RenderHtmlAsPdf` ve `RenderUrlAsPdf` gibi yöntemler kullanarak HTML dizgilerini, dosyaları ve URL'leri PDF belgelerine dönüştürmenizi sağlar.

API geliştirmede Swashbuckle kullanmanın faydaları nelerdir?

Swashbuckle, Swagger uyumlu belgeleri otomatik olarak oluşturur ve bu da açık ve tutarlı API belgeleme standartlarının korunmasına yardımcı olur. Ayrıca, Swagger UI aracılığıyla API'leri keşfetmek ve test etmek için kullanıcı dostu bir arayüz sağlar.

ASP.NET Core projesine PDF oluşturma yeteneklerini nasıl entegre edebilirim?

ASP.NET Core projesine PDF oluşturmayı entegre etmek IronPDF kullanılarak gerçekleştirilebilir. IronPDF kütüphanesini NuGet aracılığıyla yükleyin ve çeşitli içerik türlerinden PDF oluşturmak için yöntemlerini kullanın. Projenize gerekli `using` direktiflerini ve lisans anahtarlarını eklemeyi unutmayın.

Swashbuckle'da Swagger belgelerini özelleştirmek için hangi yapılandırma seçenekleri mevcut?

Swashbuckle, API sürümlemeyi ayarlama, XML yorumlarını etkinleştirme, parametre isimlendirme kurallarını tanımlama ve Swagger UI'nın görünümü ve davranışını özelleştirme gibi Swagger belgelerini özelleştirmek için çeşitli yapılandırma seçenekleri sunar.

ASP.NET Core projesinde Swashbuckle kullanırken karşılaşılan yaygın sorunları nasıl çözebilirim?

Swashbuckle ile ilgili yaygın sorunlar, proje özelliklerinde XML belgelerinin etkin olduğunu sağlayarak, doğru paket sürümlerini kontrol ederek ve `Startup.cs` dosyasında doğru kurulumun yapıldığından emin olarak çözülebilir, özellikle araya yazılımların doğru sırası kontrol edilmelidir.

C# ile PDF oluşturmak için IronPDF'in bazı özellikleri nelerdir?

IronPDF, HTML, URL ve ASP.NET içeriğini PDF'ye dönüştürme, başlık ve alt menü ekleme, PDF'leri birleştirme ve mevcut PDF dosyalarını işleme gibi özellikler sunar. C# projelerinde PDF işlemleri için kapsamlı bir kütüphanedir.

IronPDF ticari kullanım için lisanslamayı nasıl destekler?

IronPDF, ticari lisans anahtarı ile lisanslamayı destekler. IronPDF'i ücretsiz bir deneme sürümü ile deneyebilir ve lisans anahtarını genellikle `appsettings.json` dosyasında, `IronPdf` bölümüne dahil edebilir ve proje yapılandırmasında kullanabilirsiniz.

Jacob Mellor, Teknoloji Direktörü @ Team Iron
Chief Technology Officer

Jacob Mellor, Iron Software'in Teknoloji Müdürü ve C# PDF teknolojisinin öncüsü olan vizyoner bir mühendis. Iron Software’in temel kod tabanının ilk geliştiricisi olarak, şirketin ürün mimarisini kuruluşundan bu yana şekillendirdi ve CEO Cameron Rimington ile birlikte NASA, Tesla ve ...

Daha Fazlasını Oku

Iron Destek Ekibi

Haftanın 5 günü, 24 saat çevrimiçiyiz.
Sohbet
E-posta
Beni Ara