发布于 2025-01-31 18:09:44 字数 1747 浏览 2 评论 0原文

我正在尝试构建.NET 6.0 C#REST WEBS服务,接收一个字符串和三个文件,其中一个是二进制图像。 文件未保存,只有检查/评估,结果将在JSON结构中返回。 字符串可以是URL路径参数。 Web服务应在Windows和Linux Docker容器上运行。 它仅从C#客户端称为,并且无法从Internet访问。

因此,卷发看起来像这样:

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

我尝试了一种从Visual Studio 2022项目开始的方法“ ASP.NET Core-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}

但这不是解决这个问题的正确方法。

  • 文件被一个'&'分开而不是通过标头的边界,因此不可能将它们分开。
  • 以某种方式,框架应该进行分离。
  • 多部分主体是字符串,而不是字节阵列。
  • 在身体读取过程中,网络服务被阻止。

我已经阅读了很多有关如何在ASP.NET核心上载文件,WebAPI-Controller,模型视图控制器,注释,API,最小API等等,等等,等等,依此类推, 但是我仍然不确定正确的方法是什么,我找不到一个工作最小的示例。

我想知道:

  • 我应该使用哪种Visual Studio 2022启动项目类型?
  • 要使用什么框架(最小API,带有控制器的API,[APICONTROLLER]属性...)?
  • 邮政二进制多部分/表格数据的必要属性?

I'm trying to build a .NET 6.0 C# rest webservice, receiving a string and three files, one of them a binary image.
The files are not saved, just checked/evaluated and the result is returned in a json structure.
The string can be an url path parameter.
The webservice should run on windows and in a linux docker container.
It is called only from C# clients and is not accessible from the internet.

So the curl looks like that:

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

I tried an approach starting with the Visual Studio 2022 Project "ASP.NET Core-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();

With the three files containing "KeyValueContent", "TextContent" and "ImageContent", this code partially works:

Output:
Parameter:  CheckType01
MultiPart:  KeyValueContent&TextContent&ImageContent
Return:
{"check":"Ok","confidence":100}

But this can't be the correct approach to solve this, I assume.

  • The files are separated by an '&' and not by the boundary from the header, so it is not possible to separate them.
  • Somehow the framework should do the separation instead.
  • The multipart body is a string and not a byte array.
  • The webservice is blocked during the body read.

I have read a lot about how to upload files in ASP.Net Core, about webapi-controllers, model view controllers, annotations, minimal API or not and so on,
but I'm still not sure what the correct way to go is, I couldn't find a working minimal example.

I would like to know:

  • which Visual Studio 2022 starting project type should I use?
  • what framework to use (minimal api, api with controllers, [ApiController] attribute ...)?
  • the necessary attributes for POST - binary multipart/form-data?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

那伤。 2025-02-07 18:09:44

除了修复卷曲请求以读取多个文件外,您还可以使用 iformfilecollection httprequest.form.form.files.files.files(Inmject httprequest作为处理程序或使用ctx.request访问它)。

另请注意,task.run不仅在这里毫无意义,而且有害,只需将lambda处理程序标记为async

app.MapPost("/check/{checkType}", async (string checkType, HttpRequest request) =>
{
    var formFileCollection = request.Form.Files;
    foreach (var formFile in request.Form.Files)
    {
        using var openReadStream = new StreamReader(formFile.OpenReadStream());
        var readToEndAsync = await openReadStream.ReadToEndAsync();
        // do something here
    }

    ...

    return new { check = "Ok", confidence = 100 };
});

Besides fixing the curl request to read multiple file you can use IFormFileCollection returned by HttpRequest.Form.Files (inject HttpRequest as handler parameter or use ctx.Request to access it).

Also note that Task.Run not only pointless here but harmful, just mark the lambda handler as async:

app.MapPost("/check/{checkType}", async (string checkType, HttpRequest request) =>
{
    var formFileCollection = request.Form.Files;
    foreach (var formFile in request.Form.Files)
    {
        using var openReadStream = new StreamReader(formFile.OpenReadStream());
        var readToEndAsync = await openReadStream.ReadToEndAsync();
        // do something here
    }

    ...

    return new { check = "Ok", confidence = 100 };
});
锦上情书 2025-02-07 18:09:44

我检查了您的代码,您想一次发布mutiple文件,但是-data -binary允许您每个请求发布一个文件,您可以尝试使用-f发布serverl文件并从httpcontext.request.form访问文件。
您可以尝试与Postman一起尝试,您会立即找到错误的地方:

I checked your codes,you want to post mutiple files at one time,but --data-binary allows you post one file per request,you could try with -F to post serverl files and access the files from HttpContext.Request.Form.
You could try with postman,and you will find what's wrong immediately:
enter image description here
enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文