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 :
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 :
In summary, install the package "Swashbuckle.AspNetCore.Newtonsoft" and add the service "SwaggerGenNewtonsoftSupport" like :
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGenNewtonsoftSupport();