Response model for specific status codes using Swagger
Solution 1
You can try using cref="TYPE HERE" on your XML comments like this.
/// <response code="400" cref="CustomErrorModel">Bad Request</response>
B ut I would suggest using annotations that Swagger gives you.
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(OnlineMerchantQueryResponseInformation))]
attribute your Controllers with this.
Solution 2
Your signature says you're returning a HttpResponseMessage, not a data model. If you're returning an IActionResult, and you're using ASP.NET Core, you can use the "ProducesResponseType" attribute:
[ProducesResponseType(typeof(IEnumerable<YourModel>), 200)]
ProducesResponsesType is in Microsoft.AspNetCore.Mvc namespace.
See https://github.com/domaindrivendev/Swashbuckle.AspNetCore#list-operation-responses "Explicit Responses"
Solution 3
If you are using Swashbuckle, You can try
[SwaggerResponse(200, typeof(CustomModel))]
and you additionally add a comment for that response type as an optional third parameter
[SwaggerResponse(200, typeof(CustomModel), "returns a new id of the bla bla")]
Note: The attribute is in namespace Swashbuckle.AspNetCore.Annotations
Related videos on Youtube
Kaladin
Updated on August 22, 2020Comments
-
Kaladin over 3 years
I am using Swagger to document my REST API (using asp.net web api 2). Is there a way in swagger to give response models for each possible responses for a given api call? I am annotating the status code response using the xml comments like so:
/// <summary> /// Save a person /// </summary> /// <response code="200">Ok</response> /// <response code="400">Bad Request</response> /// <response code="500">Internal Server error</response> public HttpResponseMessage SavePerson() {...}
-
Ron about 9 yearsYou may want to follow this - github.com/domaindrivendev/Swashbuckle/issues/254.
-
Ian Kemp almost 4 yearsIn .NET Core .31/Swashbuckle 5,
<response code="...">...</response>
works as expected: see #3 at github.com/domaindrivendev/… for an example. -
Mirzan over 3 yearsI just simply solved the status code 200 to 400 while changing the return type from return Ok(json_structure); to return new JsonResult(json_structure); in the exception handler, and the issue is well solved ! .
-
-
Hiren Desai over 7 yearsit would be good if you can share from where you found this documentation?
-
Tipx about 6 yearsThat's only valid in Core.
-
Alexei - check Codidact almost 5 yearsThis requires NSwag.Annotations.
-
Paweł Bulwan about 4 yearsdoes the first approach here (xml comment) really work for anyone?
Cref
has some IntelliSense, but in my attempts the model does not appear in generated swagger document (despite usingswaggerGenOptions.IncludeXmlComments(xmlDocFile);
). The approach with the attribute works, however. -
robnick about 4 yearsFor .NET framework (not .NET Core) the Swashbuckle namespace to use is: using Swashbuckle.Swagger.Annotations