要在C# WebAPI中使用Swagger支持文件上传,可以按照以下步骤操作:
添加Swagger支持文件上传的NuGet包:在Visual Studio中,右键单击项目,选择“管理NuGet软件包”,搜索并安装Swashbuckle.AspNetCore包。
在Startup.cs文件中配置Swagger:在ConfigureServices方法中添加以下代码:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// 添加文件上传支持
c.OperationFilter<AddFileUploadParams>();
});
public class AddFileUploadParams : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (context.ApiDescription.HttpMethod == HttpMethod.Post)
{
var fileParameter = new OpenApiParameter
{
Name = "file",
In = ParameterLocation.Query,
Description = "Upload File",
Required = true
};
operation.Parameters.Add(fileParameter);
}
}
}
[HttpPost]
[SwaggerOperation(Summary = "Upload File")]
[Consumes("multipart/form-data")]
public async Task<IActionResult> UploadFile(IFormFile file)
{
// 处理文件上传逻辑
}
这样,您就可以在C# WebAPI中使用Swagger支持文件上传功能了。