OpenAPI / Swagger-ui: автоматически сгенерированный JSON в форме игнорирует имя параметра - PullRequest
3 голосов
/ 05 августа 2020

РЕДАКТИРОВАТЬ: нашел этот пост после публикации здесь, см. Ответ ниже

Я использую ServiceStack и его плагин OpenApi. Я не уверен, что это проблема Swagger-ui, ServiceStack или что-то в моем коде.

У меня есть конечная точка POST, где я ожидаю, что свойство Customer будет заполнено:

[Route("/api/customers/", "POST", Summary = "Creates a new customer")]
public class CreateCustomer : IReturn<CreateCustomerResponse>
{
    [ApiMember(Description = "The customer data", ParameterType = "body", IsRequired = true)]
    public Customer Customer { get; set; }
}

Класс Customer имеет ряд свойств, например «Firstname» et c.

Когда я просматриваю это в swagger-ui, я вижу, что в «Example value» отсутствует имя «Customer». что объект JSON «Клиент» должен быть помещен в:

enter image description here

If I then press "Try it out"-button, I can see that Swagger-ui sends the "Customer" object directly without specifying that it should be inside the "Customer" (I removed the backslashes and cut out properties from the Customer json for clarity):

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{  
   "PopulationRegistryNumber": "string",  
   "Firstname": "string",  
   "MiddleName": "string",  
   "Lastname": "string"
 }

What I was expected was:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '
{ "Customer": 
   {
       "PopulationRegistryNumber": "string",
       "Firstname": "string",
       "MiddleName": "string",
       "Lastname": "string"
   }
}

Now, if I remove the ServiceStack ApiMember attribute, then the Swagger-ui has the correct JSON, but it adds a separate field in the form for "Customer", that is misleading and should not be there, since it should be part of the body.

введите описание изображения здесь

Это поле «Клиент» - проблема чванства, вещь ServiceStack или что-то, чего мне не хватает?

1 Ответ

1 голос
/ 05 августа 2020

На форуме ServiceStack есть ветка , где обсуждается именно эта проблема.

Последний пост xplicit содержит решение, хотя мне не ясно, как именно атрибуты работают вместе.

Решение, которое частично решает мою проблему:

Вы можете использовать [ApiMember (ExcludeInSchema = true)] и [ApiMember (ParameterType = «model»)], чтобы исключить свойства, которые вы не хотите видеть в определениях Open API. Например,

[Route("/workflow/{ProjectId}", "POST")]
[Api(BodyParameter = GenerateBodyParameter.Always, IsRequired = true)]
public class WorkflowPostRequest : IReturn<Workflow>
{
    [ApiMember(ParameterType = "path", ExcludeInSchema = true)]
    public string ProjectId { get; set; }

    [ApiMember(ParameterType = "model")]
    public Workflow Workflow { get; set; }
} 

сгенерирует это определение Open API:

enter image description here

The forum post is здесь .

ПРИМЕЧАНИЕ:

Атрибут класса [Api(BodyParameter = GenerateBodyParameter.Always, IsRequired = true)] в моем случае не нужен, правильный JSON и смотреть в чванстве все равно работает.

Итак, в основном, все, что вам нужно сделать похоже, это изменить с ParameterType = "body" на ParameterType = "model"

Также обратите внимание, что переменные, которые находятся в пути, query et c, должны быть исключены вручную с помощью ExcludeInSchema, что раздражает, но выполнимо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...