Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger not generating model for object wrapped by IActionResult

With the following code, Swaggger UI shows the RegistrationInfo model but not the UserInfo model.

How do I get that to generate?

[Produces("application/json")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("api")]

public class UserController : Controller
{

    [HttpPost("RegisterUser")]
    public  IActionResult RegisterUser([FromBody] RegistrationInfo info)
    {
        UserInfo data =    UserData.RegisterUser(info);
        if (data != null)
        {
            return Ok(data);
        }
        return NoContent();
    }
}
like image 912
Kirsten Avatar asked Nov 01 '18 16:11

Kirsten


People also ask

What is IActionResult?

IActionResult type. The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type.

What is AddSwaggerGen?

AddSwaggerGen is an extension method to add swagger services to the collection. To configure Swagger, you invoke the method SwaggerDoc. Passing an Info object, you can define the title, description, contact information, and more in code file Startup. cs. Next open Startup.

What is documentName in Swagger?

The {documentName} refers to the name you specify in the AddSwaggerGen() method. The following code uses myapi as the name for a swagger document. builder.Services.AddSwaggerGen(options => options.SwaggerDoc("myapi", new OpenApiInfo { Title = "My API", Version = "v1" }) );

What is swashbuckle AspNetCore SwaggerGen?

AspNetCore. Swagger: a Swagger object model and middleware to expose SwaggerDocument objects as JSON endpoints. Swashbuckle. AspNetCore. SwaggerGen: a Swagger generator that builds SwaggerDocument objects directly from your routes, controllers, and models.


1 Answers

You need to use the ProducesResponseType attribute. Change your controller to this:

[Produces("application/json")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("api")]
public class UserController : Controller
{
    [ProducesResponseType(typeof(UserInfo), StatusCodes.Status200OK)]
    [HttpPost("RegisterUser")]
    public IActionResult RegisterUser([FromBody] RegistrationInfo info)
    {
        UserInfo data = UserData.RegisterUser(info);
        if (data != null)
        {
            return Ok(data);
        }

        return NoContent();
    }
}

See more here.

like image 138
Chris.ZA Avatar answered Oct 21 '22 17:10

Chris.ZA