'Incorrect method signature generated from OpenAPI definition
I just took over a project about a ticketing system and have inherited the following OpenAPI specification.
openapi: '3.0.2'
info:
title: Tickets Management
version: '1.0'
paths:
/tickets:
post:
tags:
- Create ticket
# Commented out code will generate controller method taking a NewTicket
# requestBody:
# required: true
# content:
# application/json:
# schema:
# $ref: '#/components/parameters/newTicket'
requestBody:
#The following will generate a controller method taking an object
$ref: '#/components/requestBodies/newTicket'
operationId: CreateTicket
responses:
200:
$ref: '#/components/responses/ticketId'
default:
$ref: '#/components/responses/default'
components:
parameters:
newTicket:
name: newTicket
in: path
required: true
schema:
$ref: '#/components/schemas/newTicket'
requestBodies:
newTicket:
description: Create a new ticket
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/newTicket'
schemas:
uuid:
title: uuid
type: string
format: uuid
pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
minLength: 36
maxLength: 36
shortText:
title: shortText
type: string
pattern: ^[\s\S]+$
example: "Any valid text"
minLength: 1
maxLength: 128
newTicket:
title: Input for creating a new ticket
description: Foobar
type: object
required:
- ticketDescription
properties:
creator:
ticketDescription: Description of the ticket
$ref: '#/components/schemas/shortText'
responses:
ticketId:
description: Successfully created a new ticket.
content:
application/json:
schema:
$ref: '#/components/schemas/uuid'
200:
description: Ok
content:
application/json:
schema:
title: Ok
type: string
example: Ok
default:
description: Default
content:
application/json:
schema:
title: Request not found
type: string
example: Not found
When I generate C# code, .NET 6, using NSwagStudio or Unchase OpenAPI, I get the following method for creating a new ticket:
public virtual System.Threading.Tasks.Task<System.Guid> CreateTicketAsync(object body)
{
return CreateTicketAsync(body, System.Threading.CancellationToken.None);
}
As you can see, the body is of type object, which is wrong. If I instead modify the spec to point to #/components/parameters/newTicket (see commented out code in the spec), then the input parameter is of type NewTicket. Now, I prefer to point to #/components/requestBodies/.. instead of #/components/parameters/..., but how should I do that and also get the NewTicket in the method signature?
PS: Also tried to past in the spec above into editor.swagger.io and it generates
public virtual IActionResult CreateTicket([FromBody]NewTicket body)
{
//Ommitted
}
This looks better I don't want to return an IActionResult (seems to not be .NET 6.).
Any suggestions?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
