首页 > 解决方案 > 如何在 NSwag 生成的文档中启用“text/plain”内容类型?

问题描述

我正在尝试在 AspNetCore 3.1 API 中创建一个控制器。c#,借助“NSwag.AspNetCore”13.1.3。这个控制器的目的是接收和返回纯文本(不是 json)。

控制器代码如下所示:

[HttpPost]
[Route("api/BodyTypes/JsonPlainBody")]
[Consumes("text/plain")]    
[Produces("text/plain")]
public string PlainStringBody([FromBody] string content)
{
    return content;
}   

摘自描述此服务的“swagger.json”文件:

...
"/api/BodyTypes/JsonPlainBody": {
  "post": {
    "tags": [
      "Acessórios - Operações diversas"
    ],
    "operationId": "Acessorios_PlainStringBody",
    "requestBody": {
      "x-name": "content",
      "content": {
        "application/json": {
          "schema": {
            "type": "string"
          }
        }
      },
      "required": true,
      "x-position": 1
    },
    "responses": {
      "200": {
        "description": "",
        "content": {
          "application/json": {
            "schema": {
              "type": "string"
            }
          }
        }
      }
    }
  }
}
...

此控制器在 SwaggerUI 中的表示,不允许我选择内容类型“文本/纯文本”,因此,生成格式错误的 http 请求,导致服务器返回与数据格式相关的错误(415 - 错误:不支持的媒体类型):

在此处输入图像描述

在 Postman 中测试同一个控制器时,使用“text / plain”的内容类型进行编辑,一切都按预期工作:

在此处输入图像描述

任何帮助都是最受欢迎的。

标签: c#asp.net-coreswaggernswag

解决方案


推荐阅读