Swagger Ui 之 .Net Core 上传文件

2017-09-13 10:23:59来源:网络收集作者:咖啡不加糖人点击

分享

在这篇文章中,我将向您展示如何自定义Swagger Ui以便在ASP.Net Core Web API项目中上传文件,最近想做一个Swagger文件上传,结果百度google都没有发现可行的方案,看到的更多非.Net Core版本的,最后自己摸索写了一个出来,希望微软开源力度加大,让社区更加活跃,欢迎大家一起讨论提出宝贵的意见~

最终效果图:
Swagger Ui 之 .Net Core 上传文件


项目环境: VS2017   .NetCore2.0 C#7.0  
开源框架:  RestSharp  Swagger  Nlog
第一步
新建一个过滤器,命名为SwaggerFileUploadFilter,过滤器要继承swashbuckle提供的IOperationFilter,这样我们可以用Swagger UI中的自定义文件上传控件来替换或覆盖参数。OperationId里存放着控制器名+方法名+[httpverb],这样可以实现定向过滤.
public class SwaggerFileUploadFilter : IOperationFilter
{
public void Apply(Swashbuckle.AspNetCore.Swagger.Operation operation, OperationFilterContext context)
{
if (operation.OperationId.ToLower() == "uploadgetpathpost")
{
if (operation?.Parameters?.Count > 0)
{
operation.Parameters.Clear();//Clearing parameters
}
else
{
operation.Parameters = new List();
}
operation.Parameters.Add(new NonBodyParameter
{
Name = "File",
In = "formData",
Description = "Uplaod Image",
Required = true,
Type = "file"
});
operation.Consumes.Add("multipart/form-data");
}
}
}
第二步
控制器上加上特性标签[HttpPost(“/getpath”)],以下是控制器的代码:
public class UploadController : BaseController
{
private const string _Prefix = "/upload";
///
/// 获取上传图片文件完整路径
///

[HttpPost(_Prefix + "/getpath")]
public string GetPath()
{
IFormFile file = HttpContext.Request.Form.Files[0];
string fileName = file.FileName;
string suffix = fileName.Split('.')[1];
string[] pictureFormatArray = { "png", "jpg", "jpeg", "bmp", "gif", "ico", "PNG", "JPG", "JPEG", "BMP", "GIF", "ICO" };
if (!pictureFormatArray.Contains(suffix))
{
return "the picture format not support ! you must upload files that suffix like 'png','jpg','jpeg','bmp','gif','ico'.";
}
var stream =file.OpenReadStream();
var restClient = new RestClient(ServerConfig.FileServiceUploadUrl);
var restRequest = new RestRequest(Method.POST);
restRequest.AddFile("file", stream.ReadAsBytes(), Guid.NewGuid().ToString("N") + ".png");
string path = "";
try
{
var res = restClient.Execute>(restRequest);
path = res?.Data?.Data?.Path;
path = FileUrlHelper.PathToUrl(path);
Log.Trace($"图片上传成功。path:{path ?? "null"}");
}
catch (Exception ex)
{
Log.Error($"{ex.Message }图片上传出错");
return path;
}
return path;
}
}
第三步
在Swagger配置文件,注册过滤器SwaggerFileUploadFilter
// swagger
services.AddSwaggerGen(c => {
c.DocumentFilter();
c.OperationFilter();
c.OperationFilter();
c.SwaggerDoc("v1", new Info {
Title = "Buddhism",
Version = "v1",
Description = @""
});
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "URun.Buddhism.Manage.xml");
var modelXmlPath = Path.Combine(basePath, "URun.Buddhism.Model.xml");
c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(modelXmlPath);
});


最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台