最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Swagger直接上傳文件的方法

 更新時(shí)間:2020年12月31日 08:42:12   作者:波多爾斯基  
這篇文章主要介紹了使用Swagger直接上傳文件的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

經(jīng)常使用swagger,可以通過設(shè)置[ProducesResponseType]標(biāo)記接口的返回信息;swagger也能通過接口的參數(shù)列表,自動(dòng)獲得發(fā)送的數(shù)據(jù)結(jié)構(gòu)信息。

不過有一個(gè)例外,就是上傳文件的時(shí)候,設(shè)置了[Consumes]的內(nèi)容為multi-part/form-data,但是swagger并不能正常感知是上傳文件的。代碼是這個(gè)樣子的:

關(guān)于文件上傳的細(xì)節(jié),可以看多年前我寫過一篇有關(guān)通過WEBAPI上傳文件的文章。

[Consumes("multipart/form-data")]
[ODataRoute]
[HttpPost]
public async Task<ActionResult> Post(IFormCollection collection)
{
 var file = collection.Files[0];
 if(file != null)
 {
 var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + file.FileName;
 var path = Path.Combine(_webHostEnvironment.WebRootPath, "Files", filename);
 using FileStream fileStream = new FileStream(path, FileMode.Create);
 await file.CopyToAsync(fileStream);
 var uri = "Files/" + filename;
 var fileEntity = new Models.File { Url = uri, LastModified = DateTime.Now };
 _homeworkDataContext.Files.Add(fileEntity);
 await _homeworkDataContext.SaveChangesAsync();
 return Created(WebUtility.UrlEncode(uri), fileEntity);
 }
 return BadRequest();
}

實(shí)際上,swagger一直提示,上傳的內(nèi)容是一個(gè)array類型,當(dāng)然API是沒有問題的,可以通過POSTMAN進(jìn)行發(fā)送,不過不能在網(wǎng)頁上直接操作,總覺得心里有點(diǎn)不太舒服。

方法

搜索了一下辦法,比較靠譜的,就是通過增加一個(gè)IOperationFilter來實(shí)現(xiàn)目的。

// CODE FROM https://www.talkingdotnet.com/how-to-upload-file-via-swagger-in-asp-net-core-web-api/
public class FileUploadOperation : IOperationFilter
{
 public void Apply(Operation operation, OperationFilterContext context)
 {
 if (operation.OperationId.ToLower() == "apivaluesuploadpost")
 {
  operation.Parameters.Clear();
  operation.Parameters.Add(new NonBodyParameter
  {
  Name = "uploadedFile",
  In = "formData",
  Description = "Upload File",
  Required = true,
  Type = "file"
  });
  operation.Consumes.Add("multipart/form-data");
 }
 }
}

然后,在services.ConfigureSwaggerGen()參數(shù)中,添加

options.OperationFilter<FileUploadOperation>(); 

方法的原理是通過重寫操作某個(gè)特定API的的過濾器,來實(shí)現(xiàn)對(duì)返回內(nèi)容的操作。

此方法適用于OAS2,實(shí)質(zhì)上是實(shí)現(xiàn)了這里的規(guī)范要求。

我已經(jīng)用上.NET 5.0了,自帶了swagger都支持的是OpenAPI 3,這個(gè)方法不好用了。不過思想應(yīng)該相同,首先看看OpenAPI 3的規(guī)范,文件上傳需要定義為:

requestBody:
 content:
 multipart/form-data:
 schema:
 type: object
 properties:
  fileName:
  type: string
  format: binary

這個(gè)套路和OpenAPI 2完全不一樣,需要重新設(shè)置requestBody才行。我們按照要求改造代碼。

public class FileUploadOperation : IOperationFilter
{
 public void Apply(OpenApiOperation operation, OperationFilterContext context)
 {
 //判斷上傳文件的類型,只有上傳的類型是IFormCollection的才進(jìn)行重寫。
 if (context.ApiDescription.ActionDescriptor.Parameters.Any(w => w.ParameterType == typeof(IFormCollection)))
 {
  Dictionary<string, OpenApiSchema> schema = new Dictionary<string, OpenApiSchema>();
  schema["fileName"] = new OpenApiSchema { Description = "Select file", Type = "string", Format = "binary" };
  Dictionary<string, OpenApiMediaType> content = new Dictionary<string, OpenApiMediaType>();
  content["multipart/form-data"] = new OpenApiMediaType { Schema = new OpenApiSchema { Type = "object", Properties = schema } };
  operation.RequestBody = new OpenApiRequestBody() { Content = content };
 }
 }
}

執(zhí)行之后,swagger已經(jīng)可以正常識(shí)別了,通過選擇文件即可上傳,效果如下:

參考資料

https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-5.0&tabs=visual-studio

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-5.0

https://www.talkingdotnet.com/how-to-upload-file-via-swagger-in-asp-net-core-web-api/

到此這篇關(guān)于使用Swagger直接上傳文件的方法的文章就介紹到這了,更多相關(guān)Swagger上傳文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

临颍县| 彭阳县| 龙胜| 民乐县| 东阿县| 嘉义县| 辽阳市| 郯城县| 永康市| 阿拉善右旗| 陇川县| 石首市| 南部县| 永修县| 常德市| 灵宝市| 宣化县| 巴马| 九龙县| 武夷山市| 淮阳县| 竹北市| 南昌县| 德格县| 安国市| 丰宁| 民权县| 广西| 巴彦县| 蒲城县| 安阳市| 墨脱县| 长葛市| 曲松县| 南投县| 哈巴河县| 黄陵县| 临泽县| 嫩江县| 龙门县| 中西区|