在Swagger中显示自定义属性的属性名称

kx5bkwkv  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(147)

我有一个名为UserLanguage的属性,它的类型是Language(我创建的记录),它有三个属性Name,Alpha2Code和Alpha3Code。
在我的请求模型中,我给予属性为Language,但在swagger中,它只会像这样出现

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

字符串
我想这样出现:

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


这是语言记录:

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; }
}


这是请求:

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


如何在.NET 6 Web API中实现它?

tzdcorbm

tzdcorbm1#

对于带有私有setter的属性,你需要一个过滤器:

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

字符串
在program.cs中应用它:

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


我这边没问题:


的数据

dsekswqp

dsekswqp2#

你可以这样尝试:

public class UserLanguage
{
    public string Name { get; set; }
    public string Alpha2Code { get; set; }
    public string Alpha3Code { get; set; }
}

public class YourRequestModel
{
    public string Name { get; set; }
    public UserLanguage UserLanguage { get; set; }
}

// In your Controller
[ApiController]
[Route("api/[controller]")]
public class YourController : ControllerBase
{
    [HttpPost("yourEndpoint")]
    public IActionResult YourEndpoint([FromBody] YourRequestModel model)
    {
        // Your endpoint logic here
        return Ok();
    }
}

字符串

相关问题