.Net core 3.0已经更新了,相信有挺多博主大佬们都更新了如何在.Net core3.0使用swagger,这里就不详细说了。
我们知道,如果.net core 2.x使用swagger上传文件是需要写个操作过滤器的类。
public class SwaggerFileUploadFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (!context.ApiDescription.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase) &&
!context.ApiDescription.HttpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase))
{
return;
} var fileParameters = context.ApiDescription.ActionDescriptor.Parameters.Where(n => n.ParameterType == typeof(IFormFile)).ToList(); if (fileParameters.Count < )
{
return;
} operation.Consumes.Add("multipart/form-data"); foreach (var fileParameter in fileParameters)
{
var parameter = operation.Parameters.Single(n => n.Name == fileParameter.Name);
operation.Parameters.Remove(parameter);
operation.Parameters.Add(new NonBodyParameter
{
Name = parameter.Name,
In = "formData",
Description = parameter.Description,
Required = parameter.Required,
Type = "file"
});
}
}
}
需要在startup类中配置:
这样上传文件的api就有选择文件的按钮了:
然后升级到.net core 3.0 ,swagger目前4.x版本不支持,只能下5.x的预览版,然后一堆报错。首先配置中的Info 需要改成OpenApiInfo:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Web API", Version = "v1" });
var xmlPath = Path.Combine(AppContext.BaseDirectory, "swagger.xml");
c.IncludeXmlComments(xmlPath);
c.OperationFilter<SwaggerFileUploadFilter>();
});
改成:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Web API", Version = "v1", Description = "Web API" });
var xmlPath = Path.Combine(AppContext.BaseDirectory, "swagger.xml");
c.IncludeXmlComments(xmlPath);
});
而且swagger 5.0版本不需要手动写过滤器类,也就是
SwaggerFileUploadFilter
上文提到的这个类。
直接正常写api就可以了,不过IFormFile参数一定不要加[FromBody]这个特性。就像这样:
/// <summary>
/// 上传文件
/// </summary>
/// <param name="formFile">文件</param>
/// <returns></returns>
[HttpPost]
public IActionResult test(IFormFile formFile)
{
return Ok("靓仔");
}
然后打开swagger就可以看到:
结束!