我正在try 建立一个.Net 6.0 C#rest webservice,接收一个字符串和三个文件,其中一个是二进制图像.
curl 看起来是这样的:
curl -X POST -H "Content-Type: multipart/form-data; boundary=------------------------d74496d66958873e" \
--data-binary "@KeyValue.json" \
--data-binary "@Text.txt" \
--data-binary "@Image.tif" \
http://localhost:5000/check/CheckType01
我try 了一种从Visual Studio 2022项目"ASP.NET核心Web Api"开始的方法
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapPost("/check/{checkType}", (string checkType, HttpContext ctx) =>
{
ctx.Request.EnableBuffering();
ctx.Request.Body.Position = 0;
var reader = new StreamReader(ctx.Request.Body);
var body = Task.Run(async () => await reader.ReadToEndAsync().ConfigureAwait(false));
Console.WriteLine("Parameter: " + checkType);
Console.WriteLine("MultiPart: " + body.Result);
return new { check = "Ok", confidence = 100 }; ;
});
app.Run();
对于包含"KeyValueContent"、"TextContent"和"ImageContent"的三个文件,此代码部分工作:
Output:
Parameter: CheckType01
MultiPart: KeyValueContent&TextContent&ImageContent
Return:
{"check":"Ok","confidence":100}
但我认为这不是解决这个问题的正确方法.
- 文件之间用"&;分隔"而不是通过标题的边界,因此无法将它们分开.
- 框架应该以某种方式进行分离.
- 多部分正文是字符串,而不是字节array.
- webservice在正文读取期间被阻止.
我读了很多关于如何在ASP中上传文件的书.Net核心,关于webapi控制器、模型视图控制器、注释、是否使用最小API等,
我想知道:
- 我应该使用哪种Visual Studio 2022启动项目类型?
- 使用什么框架(最小api、带控制器的api、[ApiController]属性?
- 后二进制多部分/表单数据的必要属性?