Cấu hình Swagger trong .NET Core 2.1

1. Tạo ứng dụng Web .NET Core mới với mẫu API

2. Cài đặt gói NuGet: Swashbuckle.AspNetCore

Install-Package Swashbuckle.AspNetCore -Version 4.0.1

Hoặc mở giao diện quản lý NuGet và tìm kiếm Swashbuckle.AspNetCore (phiên bản tôi sử dụng là 4.0.1)

3. Đăng ký dịch vụ phụ thuộc

Sửa phương thức ConfigureServices trong file Startup.cs

public void ConfigureServices(IServiceCollection serviceCollection)
{
    serviceCollection.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    #region Cau hinh Swagger
    serviceCollection.AddSwaggerGen(config =>
    {
        #region Thong tin co ban phan dau

        config.SwaggerDoc("v1", new Info
        {
            Version = "v1.1.0",
            Title = "WebAPI",
            Description = "Tai lieu huong dan API",
            TermsOfService = "None",
            Contact = new Swashbuckle.AspNetCore.Swagger.Contact 
            { 
                Name = "NinaMua", 
                Email = "791016081@qq.com", 
                Url = "http://www.cnblogs.com/NinaMua" 
            }
        });
        #endregion

    });
    #endregion

}
ConfigureServices

4. Sử dụng middleware

public void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory)
{
    if (hostingEnvironment.IsDevelopment())
    {
        applicationBuilder.UseDeveloperExceptionPage();
    }
    else
    {
        applicationBuilder.UseHsts();
    }

    applicationBuilder.UseHttpsRedirection();

    loggerFactory.AddNLog(); // them NLog
    hostingEnvironment.ConfigureNLog("nlog.config"); // doc file cau hinh Nlog

    #region Swagger
    applicationBuilder.UseSwagger();
    applicationBuilder.UseSwaggerUI(settings =>
    {
        settings.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
    });
    #endregion

    applicationBuilder.UseMvc();
}
Configure

5. Kết quả

Khi khởi động ứng dụng, trang mặc định sẽ hiển thị như sau

Thay đổi api/value thành swagger

Để ứng dụng tự động mở Swagger khi chạy, cần sửa file launchSettings.json

Thay đổi launchUrl thành Swagger

"profiles": {
  "IIS Express": {
    "commandName": "IISExpress",
    "launchBrowser": true,
    "launchUrl": "swagger",
    "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development"
    }
  },
launchSettings.json

Chạy chương trình để thấy trang mặc định đã chuyển sang Swagger

7. Mô tả giao diện

Nhấp chuột phải vào project → Properties → Build → Generate XML documentation file

Tương tự với các thư viện chứa lớp thực thể cũng cần tạo tài liệu XML

Lưu ý: Hai file XML này cần nằm trong cùng thư mục bin

Thêm mô tả cho controller

//<summary> //<para>Dang nhap he thong</para> //</summary> //<returns>Ket qua dang nhap</returns> \[Route("Authentication/Login")\] \[HttpGet\] public ApiResponse Login() { return new ApiResponse { StatusCode = 0, Info = "123", Result = "Day la du lieu tra ve" }; }
/// <summary>
/// Lop tra ve thong tin chung
/// </summary>
public class ApiResponse
{
    /// <summary>
    /// Ma ket qua thuc thi
    /// </summary>
    public int StatusCode { get; set; }
    /// <summary>
    /// Thong bao tra ve
    /// </summary>
    public string Info { get; set; }
    /// <summary>
    /// Tap hop du lieu ket qua
    /// </summary>
    public object Result { get; set; }
}
Lớp trả về

Sau đó chỉnh sửa phương thức ConfigureServices trong lớp Startup

public void ConfigureServices(IServiceCollection serviceCollection)
{

    serviceCollection.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    #region Cau hinh Swagger
    serviceCollection.AddSwaggerGen(config =>
    {
        #region Thong tin co ban phan dau

        config.SwaggerDoc("v1", new Info
        {
            Version = "v1.1.0",
            Title = "WebAPI",
            Description = "Tai lieu huong dan API",
            TermsOfService = "None",
            Contact = new Swashbuckle.AspNetCore.Swagger.Contact 
            { 
                Name = "NinaMua", 
                Email = "791016081@qq.com", 
                Url = "http://www.cnblogs.com/NinaMua" 
            }
        });
        #endregion

        #region Them dich vu doc ghi chu
        // Them ghi chu cho cac controller bang cach su dung SwaggerDocTag
        // config.DocumentFilter<SwaggerDocTag>();
        var rootPath = AppDomain.CurrentDomain.BaseDirectory;

        var controllerXmlPath = Path.Combine(rootPath, "TestApi.xml");
        if (System.IO.File.Exists(controllerXmlPath))
            config.IncludeXmlComments(controllerXmlPath, true); // ghi chu cho controller (true de hien thi ghi chu controller)

        var modelXmlPath = Path.Combine(rootPath, "TestEntity.xml");
        if (System.IO.File.Exists(modelXmlPath))
            config.IncludeXmlComments(modelXmlPath); // ghi chu cho lop thuc the
        #endregion

    });
    #endregion

}
ConfigureServices

Chạy chương trình để kiểm tra

8 Quyền truy cập giao diện

Cần thêm phần xác thực vào middleware

public void ConfigureServices(IServiceCollection serviceCollection)
{
    serviceCollection.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    #region Cau hinh Swagger
    serviceCollection.AddSwaggerGen(config =>
    {
        #region Thong tin co ban phan dau

        config.SwaggerDoc("v1", new Info
        {
            Version = "v1.1.0",
            Title = "WebAPI",
            Description = "Tai lieu huong dan API",
            TermsOfService = "None",
            Contact = new Swashbuckle.AspNetCore.Swagger.Contact 
            { 
                Name = "NinaMua", 
                Email = "791016081@qq.com", 
                Url = "http://www.cnblogs.com/NinaMua" 
            }
        });
        #endregion

        #region Thong tin xac thuc quyen

        // Them thong tin xac thuc toan cuc bat buoc, ten phai giong voi ten trong AddSecurityDefinition
        var securityRequirements = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } } };
        config.AddSecurityRequirement(securityRequirements);

        config.AddSecurityDefinition("Bearer", new ApiKeyScheme
        {
            Description = "Dinh dang|Bearer {token}",
            Name = "Authorization", // ten tham so mac dinh cua jwt
            In = "header", // jwt mac dinh luu thong tin Authorization trong header
            Type = "apiKey"
        });

        #endregion

        #region Them dich vu doc ghi chu
        // Them ghi chu cho cac controller bang cach su dung SwaggerDocTag
        // config.DocumentFilter<SwaggerDocTag>();
        var rootPath = AppDomain.CurrentDomain.BaseDirectory;

        var controllerXmlPath = Path.Combine(rootPath, "TestApi.xml");
        if (System.IO.File.Exists(controllerXmlPath))
            config.IncludeXmlComments(controllerXmlPath, true); // ghi chu cho controller

        var modelXmlPath = Path.Combine(rootPath, "TestEntity.xml");
        if (System.IO.File.Exists(modelXmlPath))
        config.IncludeXmlComments(modelXmlPath); // ghi chu cho lop thuc the
        #endregion

    });
    #endregion

}
ConfigureServices

Sau khi sửa xong, chạy chương trình sẽ thấy xuất hiện biểu tượng khóa nhỏ bên cạnh các giao diện

Nhấp vào khóa sẽ hiển thị cửa sổ như sau

Chúng ta tạm dừng ở đây trước, phần quyền hạn sẽ xử lý sau

Thẻ: aspnet-core Swagger Swashbuckle web-api Configuration

Đăng vào ngày 27 tháng 6 lúc 19:04