![](/img/trans.png)
[英]ASP.NET Core - Swashbuckle not creating swagger.json file
[英].net Core & Swashbuckle/Swagger: How to provide raw json example?
我有一个 WebAPI controller,其操作返回 JSON 架构。 这个JSON的返回值是不能序列化创建的,所以我设计了如下操作方法:
[HttpGet("{serviceName}/contract")]
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(object))]
public IActionResult GetContract(string serviceName)
{
return Content("{ \"type\": \"object\" }", "application/json"); // for example ...
}
现在我想要 Swagger 的一个或一些记录的返回值。但我无法做到这一点。 有SwaggerRequestExample
属性,但如前所述,这需要一个返回类型,这在我的情况下不适用。
基本上我寻找一种类似的方式(只是动态的):
[SwaggerResponseExample((int)HttpStatusCode.OK, "{\"anyJson\": \"Yes, I am!\"}")]
或者当然,更好的是:
[SwaggerResponseExample((int)HttpStatusCode.OK, RawJsonFabricType="TypeName", RawJsonStaticMethod="MethodName")]
用例:我需要在操作方法中返回的 JSON 模式存储在数据库中,而不是在程序代码本身中创建的。
这种 JSON 模式值的具体示例是:
{
"$id": "https://example.com/person.schema.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"lastName": {
"type": "string",
"description": "The person's last name."
},
"age": {
"description": "Age in years which must be equal to or greater than zero.",
"type": "integer",
"minimum": 0
}
}
}
帮助将不胜感激。 谢谢!
我正在使用 c#.net 核心 6。
在尝试之后我找到了解决方案:
第一:添加ExampleProvider
并使用通用类型JsonDocument
(来自System.Text.Json
):
public class ServiceDemandContractExampleProvider : IExamplesProvider<JsonDocument>
{
/// <inheritdoc/>
public JsonDocument GetExamples()
{
var jsonToShow = JsonDocument.Parse(@"{
""$id"": ""https://example.com/person.schema.json"",
""$schema"": ""https://json-schema.org/draft/2020-12/schema"",
""title"": ""Person"",
""type"": ""object"",
""properties"": {
""firstName"": {
""type"": ""string"",
""description"": ""The person's first name.""
},
""lastName"": {
""type"": ""string"",
""description"": ""The person's last name.""
},
""age"": {
""description"": ""Age in years which must be equal to or greater than zero."",
""type"": ""integer"",
""minimum"": 0
}
}
}");
return jsonToShow;
}
}
在JsonDocument.Parse
中放置任何 JSON(在我的例子中是从数据库加载的内容)。
然后在操作方法中添加如下属性:
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(object))]
[SwaggerResponseExample((int)HttpStatusCode.OK, typeof(ServiceDemandContractExampleProvider))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.