Asp.net web api 如何使用Swashback实现OpenAPI只读和写
我正在.NET5.0WebAPI中使用Swashback(6.1.1)。我还在学习,但我想实现一个类,其中某些属性仅在使用Asp.net web api 如何使用Swashback实现OpenAPI只读和写,asp.net-web-api,openapi,swashbuckle,Asp.net Web Api,Openapi,Swashbuckle,我正在.NET5.0WebAPI中使用Swashback(6.1.1)。我还在学习,但我想实现一个类,其中某些属性仅在使用GET进行“读取”时有效,而其他属性在使用POST进行“写入”时有效。根据报告: 您可以使用readOnly和writeOnly关键字将特定属性标记为只读或只读。例如,当GET返回的属性多于POST中使用的属性时,这非常有用–您可以在GET和POST中使用相同的模式,并将额外的属性标记为只读。只读属性包含在响应中,但不包含在请求中;writeOnly属性可以在请求中发送,但不
GET
进行“读取”时有效,而其他属性在使用POST
进行“写入”时有效。根据报告:
您可以使用readOnly和writeOnly关键字将特定属性标记为只读或只读。例如,当GET返回的属性多于POST中使用的属性时,这非常有用–您可以在GET和POST中使用相同的模式,并将额外的属性标记为只读。只读属性包含在响应中,但不包含在请求中;writeOnly属性可以在请求中发送,但不包含在响应中
这正是我想要实现的。然而,我正在努力让Swashback使用readOnly
和writeOnly
keyworks生成OpenAPI规范
例如:
public class testDetails
{
public string commonProperty { get; set; }
public string readOnlyProperty { get; set; }
public string writeOnlyProperty { get; set; }
}
[ProducesResponseType(StatusCodes.Status200OK)]
[HttpGet("Get")]
public IActionResult Get([FromQuery] testDetails details)
{
Debug.WriteLine($"commonProperty is {details.commonProperty}");
Debug.WriteLine($"readOnlyProperty is {details.readOnlyProperty}");
Debug.WriteLine($"writeOnlyProperty is {details.writeOnlyProperty}");
return Ok();
}
我希望在生成的swagger.json
中将readOnlyProperty
标记为readOnly
,并将writeOnlyProperty
标记为writeOnly
实际上,writeOnlyProperty
不应显示为任何GET
的属性(但会显示为POST
/PUT
),相反,readOnlyProperty
应可用于GET
而不是POST
我尝试添加一个System.ComponentModel
[ReadOnly
]属性,但没有效果。我还尝试将访问器更改为
public class testDetails
{
public string commonProperty { get; set; }
public string readOnlyProperty { get; internal set; }
public string writeOnlyProperty { internal get; set; }
}
。。。但这最终会完全隐藏属性。所有这些都不会影响代码的实际操作,但我仍然希望属性只在需要的地方可写,否则为只读-正如OpenAPI规范所描述的那样。有没有一种方法可以在不创建单独的“读写类”的情况下实现这一点?您可以从软件包
swashback.AspNetCore.Annotations>中为只读和只读属性添加注释。这将允许您使用readOnly
和writeOnly
关键字生成OpenAPI规范,还可以对Swagger UI隐藏属性
遵循以下步骤:
将以下Nuget软件包安装到ASP.NET核心应用程序中
在Startup.cs
的ConfigureServices
方法中,在Swagger config块中启用注释:
向模型添加属性:
公共类测试详细信息
{
公共字符串CommonProperty{get;set;}
[招摇过市模式(只读=true)]
公共字符串只读属性{get;set;}
[虚张声势模式(WriteOnly=true)]
公共字符串WriteOnlyProperty{get;set;}
}
您的控制器可能看起来像:
[ApiController]
[路线(“[控制器]”)]
公共类数据控制器:ControllerBase
{
私有TestDetails TestDetails=newtestdetails()
{
CommonProperty=“Common prop value”,
ReadOnlyProperty=“只读属性值”,
WriteOnlyProperty=“WriteOnly属性值”
};
公共数据控制器()
{
}
[HttpGet]
[产品响应类型(typeof(TestDetails),(int)HttpStatusCode.OK)]
public IActionResult Get()
{
返回Ok(testDetails);
}
[HttpPost]
[产品响应类型((int)HttpStatusCode.OK)]
公共IActionResult帖子([FromBody]TestDetails)
{
返回Ok();
}
}
Install-Package Swashbuckle.AspNetCore.Annotations
services.AddSwaggerGen(c =>
{
...
c.EnableAnnotations();
});