简体   繁体   中英

C# OpenApi Nswag Client Generation Complex Class is empty

I am trying to create a Client with the help of the latest versions of nswag and .net6.

Many class schemas are empty if they are more complex. Something that was working in the older versions.

This is one of the classes:

public class ObjectDetail : ObjectInfo
{
    public IDictionary<int, string> Descriptions;
    public ObjectStatus Status;
    public Dictionary<string, ParamRecItem> ParamRec;
    public Dictionary<string, StatusRecItem> StatusRec;

    public ObjectDetail()
    {
        Descriptions = new Dictionary<int, string>();
        ParamRec = new Dictionary<string, ParamRecItem>();
        StatusRec = new Dictionary<string, StatusRecItem>();
    }
}

This is the Base Class

public class ObjectInfo
{
    [JsonRequired] public int Id;
    [JsonRequired] public int No;

    public int? ParentId;
    public string Path;
    public string Name;
    public string Description;
    public string Info;
    public ClassInfo Class;
    public PlcInfo Plc;
}

My API Controller looks like this:

// [ApiLogging]
[HttpGet]
[Route("[controller]_getObjectDetailByName/{name}")]
[ProducesResponseType(typeof(ObjectDetail), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public ActionResult GetObjectDetailByName(string name)
{
    ObjectDetail result = scadaService.GetObjectDetailByName(name);
    return result == null ? BadRequest() : Ok(result);
}

The outcome of the swagger.json schema is empty:

 "ObjectDetail": {
    "type": "object",
    "additionalProperties": false
  }

Program.cs is the standard

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

What is the problem and how can I solve it?

From the version 5, Swashbuckle use "System.Text.Json" (to replace "Newtonsoft.Json"). But "System.Text.Json" ignore class's field. See this github issue to more detail:

No possibility of rendering non-property fields in models?

The best solution is to replace fields by properties like:

public class ObjectInfo
{
    [JsonRequired]
    public int Id {get; set;}
    [JsonRequired]
    public int No {get; set;}

    public int? ParentId {get; set;}
    ...
}

But if it's too much work, you configure Swashbuckle to use "Newtonsoft.Json" like explained in this documentation:

System.Text.Json (STJ) vs Newtonsoft

In summary, install the package "Swashbuckle.AspNetCore.Newtonsoft" and add the service "SwaggerGenNewtonsoftSupport" like:

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGenNewtonsoftSupport();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM