如何使用 Swashbuckle 提供模型文档和示例值?

问题描述 投票:0回答:1

我已经使用 Web API 2 (MVC 5) 创建了一个 API 方法,如下所示:

/// <summary>
/// Import all of the jobs for the given organisation. This method assumes that all of the organisation's active jobs are present in the jobs array.
/// To delete a job, simply exclude it from the jobs array. To delete all of the jobs, pass an empty array
/// </summary>
/// <param name="org">Organisation Id, provided by Shopless team</param>
/// <param name="jobs">Full list of jobs which should be imported, json array</param>
/// <response code="200">Jobs list have been queued for import (includes validation errors if any)</response>
/// <response code="401">Access to this organisation was denied</response>
/// <response code="404">Invalid organisation id</response>
[SwaggerResponse(HttpStatusCode.BadRequest)]
[SwaggerResponse(HttpStatusCode.NotFound)]
[SwaggerResponse(HttpStatusCode.Unauthorized)]
[HttpPost]
[Route("org/{org}/jobs/full-import")]
public IHttpActionResult FullImport(long org, [FromBody] List<JobApiDto> jobs)
{
    if (!ModelState.IsValid)
    {
        return BadRequest("Jobs array is invalid");
    }
    else if (org < 1)
    {
        return NotFound("Invalid organisation id");
    }
    else if (!((ClaimsPrincipal)User).HasReadWriteAccessToOrganisation(org))
    {
        return Unauthorized("Access to this organisation was denied");
    }

    _apiProductUploader.Upload(org, jobs, out string message);
    return Accepted(message);
}

上述方法接受

JobApiDto
的列表:

public class JobApiDto
{
   /// <summary>
   /// Job Id (unique id assigned to the job by the API consumer)
   /// </summary>
   /// <example>e5f52dae-e008-49bd-898b-47b5f1a52f40</example>
   public string UniqueThirdPartyId { get; set; }

   /// <summary>
   /// Short description which will be displayed in search result
   /// </summary>
   /// <example>Competitive salary, great team, cutting edge technology!</example>
   public string Synopsis { get; set; }

   // more properties

这就是 Swagger 文档的样子:

当我展开

OrganisationJobs
动作时:

这是模型选项卡:

如您所见,控制器的 xml 文档为 API 方法生成了正确的描述,但我无法理解为什么我为模型提供的描述(即

JobApiDto
)没有显示?

此外,当我单击“示例值”时,什么也没有发生。

c# asp.net-mvc-5 swagger asp.net-web-api2 swashbuckle
1个回答
1
投票

感谢亚历山大指出这个答案。

我安装了 Swashbuckle.Examples Nuget 包。 (文档很棒。)

我不得不用以下方式注释控制器:

[SwaggerRequestExample(typeof(JobApiDto), typeof(ListJobApiDtoExample), jsonConverter: typeof(StringEnumConverter))]

这就是控制器定义的样子:

/// <summary>
/// Import all of the jobs for the given organisation. This method assumes that all of the organisation's active jobs are present in the jobs array.
/// To delete a job, simply exclude it from the jobs array. To delete all of the jobs, pass an empty array
/// </summary>
/// <param name="org">Organisation Id, provided by Shopless team</param>
/// <param name="jobs">Full list of jobs which should be imported, json array</param>
[SwaggerRequestExample(typeof(JobApiDto), typeof(ListJobApiDtoExample), jsonConverter: typeof(StringEnumConverter))]
[SwaggerResponse(HttpStatusCode.OK, Description = "Jobs array has been queued for import", Type = typeof(ImportResponse))]
[SwaggerResponseExample(HttpStatusCode.OK, typeof(ImportResponseExamples))]
[SwaggerResponse(HttpStatusCode.BadRequest, "Jobs array is invalid")]
[SwaggerResponse(HttpStatusCode.NotFound, "Invalid organisation id")]
[SwaggerResponse(HttpStatusCode.Unauthorized, "Access to this organisation was denied")]
[HttpPost]
[Route("org/{org}/jobs/full-import")]
public IHttpActionResult FullImport(long org, [FromBody] List<JobApiDto> jobs)
{
    if (!ModelState.IsValid)
    {
        return BadRequest("Jobs array is invalid");
    }
    else if (org < 1)
    {
        return NotFound("Invalid organisation id");
    }
    else if (!((ClaimsPrincipal)User).HasReadWriteAccessToOrganisation(org))
    {
        return Unauthorized("Access to this organisation was denied");
    }

    _apiProductUploader.Upload(org, jobs, out ImportResponse importResponse);
    return Accepted(importResponse);
}

这里是

ListJobApiDtoExample
的实现:

public class ListJobApiDtoExample : IExamplesProvider
{
    public object GetExamples()
    {
        return new JobApiDto()
        {
            UniqueThirdPartyId = "e5f52dae-e008-49bd-898b-47b5f1a52f40",
            CategoryId = 1183,
            Title = "Senior Software Developer",
            Description = "Example company is looking for a senior software developer... more details about the job",
            Reference = "",
            Synopsis = "Competitive salary, great team, cutting edge technology!",
            MinSalary = 120000,
            MaxSalary = 140000,
            SalaryPer = "Per annum",
            DisplaySalary = true,
            CustomSalaryText = "plus bonus",
            WorkType = "Full time",
            Location = "Wellington CBD",
            ContactName = "John Smith",
            ContactEmail = "[email protected]",
            ContactPhoneNumber = "021 123 456 789",
            ApplicationUrl = "",
            LogoUrl = "https://www.example-company.com/my-company-logo",
            YouTubeVideo = "https://www.youtube.com/watch?v=khb7pSEUedc&t=1s",
            StartDate = null,
            PostedAt = null
        };
    }
}

请注意,我还有一个 API 返回类型的示例,

ImportResponse
。与之前的模型类似,我在控制器上有这个注释:

[SwaggerResponseExample(HttpStatusCode.OK, typeof(ImportResponseExamples))] 

这是植入:

public class ImportResponseExamples : IExamplesProvider
{
    public object GetExamples()
    {
        return new ImportResponse()
        {
            Message = "Products are queued to be imported"
        };
    }
}

现在,文档正确显示了示例:

© www.soinside.com 2019 - 2024. All rights reserved.