如何使用 Swashbuckle 实现 OpenAPI readOnly 和 writeOnly

Ken*_*enD 7 asp.net-web-api swashbuckle openapi

我正在 .Net 5.0 Web API 中使用 Swashbuckle (6.1.1)。我仍在学习,但我想实现一个类,其中某些属性仅在使用 a 进行“读取”时有效GET,而其他属性仅在使用 a 进行“写入”时有效POST。根据OpenAPI 规范

\n
\n

您可以使用 readOnly 和 writeOnly 关键字将特定属性标记为只读或只写。这很有用,例如,当 GET 返回的属性多于 POST \xe2\x80\x93 中使用的属性时,您可以在 GET 和 POST 中使用相同的架构,并将额外的属性标记为只读。readOnly 属性包含在响应中,但不包含在请求中,writeOnly 属性可以在请求中发送,但不包含在响应中。

\n
\n

这正是我想要实现的目标。然而,我正在努力让 Swashbuckle 使用readOnlywriteOnlykeyworks 生成 OpenAPI 规范。

\n

例如:

\n
    public class testDetails\n    {            \n        public string commonProperty { get; set; }           \n        public  string readOnlyProperty { get; set; }\n        public string writeOnlyProperty {  get; set; }\n    }\n\n    [ProducesResponseType(StatusCodes.Status200OK)]    \n    [HttpGet("Get")]\n    public IActionResult Get([FromQuery] testDetails details)\n    {\n        Debug.WriteLine($"commonProperty is {details.commonProperty}");\n        Debug.WriteLine($"readOnlyProperty is {details.readOnlyProperty}");\n        Debug.WriteLine($"writeOnlyProperty is {details.writeOnlyProperty}");\n        return Ok();\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

我希望readOnlyProperty被标记为readOnly,并在生成的文件中writeOnlyProperty被标记为writeOnlyswagger.json.

\n

实际上,writeOnlyProperty不应作为 any 的属性出现GET(但会出现POST/ PUT),相反,readOnlyProperty应该可用于 aGET但不可用于 a POST

\n

我尝试添加System.ComponentModel [ReadOnly] 属性,但没有效果。我也尝试过将访问器更改为

\n
 public class testDetails\n    {            \n        public string commonProperty { get; set; }           \n        public  string readOnlyProperty { get; internal set; }\n        public string writeOnlyProperty {  internal get; set; }\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

...但这最终会完全隐藏属性。这些都不会影响代码的实际操作,但我仍然希望属性只能在需要的地方可写,否则只读 - 正如 OpenAPI 规范所描述的那样。有没有办法做到这一点,而不创建单独的“读写类”?

\n

rus*_*gil 9

您可以使用包中的SwaggerSchemaAttribute注释只读和只写属性Swashbuckle.AspNetCore.Annotations。这将允许您使用readOnlywriteOnly关键字生成 OpenAPI 规范,并隐藏 Swagger UI 中的属性。

按着这些次序:

  1. 将以下 Nuget 包安装到 ASP.NET Core 应用程序中。
Install-Package Swashbuckle.AspNetCore.Annotations
Run Code Online (Sandbox Code Playgroud)
  1. ConfigureServices的方法中Startup.cs,在 Swagger 配置块中启用注释:
services.AddSwaggerGen(c =>
{
   ...

   c.EnableAnnotations();
});
Run Code Online (Sandbox Code Playgroud)
  1. 向您的模型添加属性:
Install-Package Swashbuckle.AspNetCore.Annotations
Run Code Online (Sandbox Code Playgroud)

您的控制器可能如下所示:

services.AddSwaggerGen(c =>
{
   ...

   c.EnableAnnotations();
});
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的一件事:如果您有一个标记为必需的属性,这将阻止此只读注释产生任何效果 (2认同)