Search code examples
c#.netasp.net-coreswaggerswagger-ui

Display properties name for custom properties in Swagger


I have a property named UserLanguage whose type is Language ( a record that I created ) which has three properties Name,Alpha2Code and Alpha3Code.

So in my request models, I give property as Language but on swagger, it only appears like this

{
  "name" : "",
  "userlanguage" : {}
}

I want to appear like this :

 {
      "name" : "",
      "userLanguage" : {
          "name" : "",
          "alpha2Code" : "",
          "alpha3Code" : ""
       }
 }

This is the language record:

public record Language
{
    public static readonly Language None = new(string.Empty, string.Empty, string.Empty);
    
    private Language(
        string alpha2Code, 
        string alpha3Code,
        string name)
    {
        Name = name;
        Alpha2Code = alpha2Code;
        Alpha3Code = alpha3Code;
    }
    public string Alpha2Code { get; private set; } = string.Empty;
    public string Alpha3Code { get; private set; } = string.Empty;
    public string? Name { get; private set; }
}

This is the request:

public sealed record UserDetailsRequest(
    string Name,
    Language UserLanguage
);

How can I achieve it in .NET 6 Web API?


Solution

  • For the properties with a private setter,you would need a filter:

     public class AddPrivateSetPropertyFilter : ISchemaFilter
     {
         public void Apply(OpenApiSchema schema, SchemaFilterContext context)
         {
             if (schema?.Properties?.Count > 0)
                 schema.Properties.Values.SingleOrDefault(v => v.ReadOnly = false);
         }
     }
    

    Apply it in program.cs:

    builder.Services.AddSwaggerGen(c=> c.SchemaFilter<AddPrivateSetPropertyFilter>());
    

    It's ok onmyside:

    enter image description here