如何让Swagger UI为读取Request.Body的ASP.NET Core接口提供请求体文本框?
解决Swagger未生成请求体输入框的问题
针对你的场景,有几种简便方法可以让Swagger UI显示请求体的<textarea>输入框:
方法一:使用Swagger注解特性(推荐)
先安装Swashbuckle.AspNetCore.SwaggerAnnotations NuGet包,然后在接口方法上添加[SwaggerRequestBody]特性,手动声明请求体信息:
using Swashbuckle.AspNetCore.Annotations; [HttpPost("event")] [SwaggerRequestBody("请求体内容", Required = true, Type = typeof(string))] public Task PostEvent(string clientId) { _someService.HandleEvent(clientId, Request.Body); }
该特性会告知Swagger生成对应类型的请求体输入区域,字符串类型会自动渲染为<textarea>。
方法二:添加占位[FromBody]参数(简单粗暴)
如果不想额外安装包,可临时添加一个不实际使用的[FromBody]参数,仅用于Swagger识别请求体:
[HttpPost("event")] public Task PostEvent(string clientId, [FromBody] string _) { _someService.HandleEvent(clientId, Request.Body); }
注意:ASP.NET Core默认只能读取一次Request.Body流,需配置允许重复读取,在Program.cs中添加:
// 启用请求体可重复读取 app.Use(async (context, next) => { context.Request.EnableBuffering(); await next(); }); // 或关闭参数绑定自动推断,避免[FromBody]参数消耗流 builder.Services.Configure<ApiBehaviorOptions>(options => { options.SuppressInferBindingSourcesForParameters = true; });
方法三:自定义操作过滤器(灵活可控)
如果需要针对特定接口定制Swagger文档,可编写操作过滤器手动添加请求体定义:
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Net; public class AddRequestBodyFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { // 匹配目标接口 if (context.ApiDescription.HttpMethod == HttpMethod.Post.Method && context.ApiDescription.RelativePath?.EndsWith("event") == true) { operation.RequestBody = new OpenApiRequestBody { Description = "自定义请求体描述", Required = true, Content = new Dictionary<string, OpenApiMediaType> { ["text/plain"] = new OpenApiMediaType { Schema = new OpenApiSchema { Type = "string" } }, ["application/json"] = new OpenApiMediaType { Schema = new OpenApiSchema { Type = "string" } } } }; } } }
然后在Swagger注册时添加该过滤器:
builder.Services.AddSwaggerGen(c => { c.OperationFilter<AddRequestBodyFilter>(); });
内容的提问来源于stack exchange,提问作者Jacob Stamm
相关产品推荐
相关产品推荐

