gpt4 book ai didi

c# - 使用 HttpClient 将文件上传到 ASP.NET WebApi 2

转载 作者:行者123 更新时间:2023-11-30 20:25:18 25 4
gpt4 key购买 nike

我有这个 HttpClient 用于发布文件:

var content = new MultipartFormDataContent(Guid.NewGuid().ToString())
{
new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json")
};

foreach (var file in files)
{
var byteContent = new ByteArrayContent(file.Data);

content.Add(byteContent, file.FieldName, file.FileName);
}

return await _client.PostAsync(_apiUrl + apiRelativeUrl, content);

但是我的 ASP.NET WebApi Controller 给出错误 500,但出现以下异常:

System.IO.IOException: Unexpected end of MIME multipart stream. MIME multipart message is not complete.

WebApi Controller 代码是

if (Request.Content.IsMimeMultipartContent())
{
var multipart = await Request.Content.ReadAsMultipartAsync(); //this line throws the exception
var fileContent = multipart.Contents.FirstOrDefault();

if (fileContent != null)
{
var photo = await fileContent.ReadAsByteArrayAsync();
}
}

我做错了什么?

最佳答案

基本上我使用自定义流来附加 asp.net web api 期望的换行符。

Stream reqStream = Request.Content.ReadAsStreamAsync().Result;
MemoryStream tempStream = new MemoryStream();
reqStream.CopyTo(tempStream);



tempStream.Seek(0, SeekOrigin.End);
StreamWriter writer = new StreamWriter(tempStream);
writer.WriteLine();
writer.Flush();
tempStream.Position = 0;


StreamContent streamContent = new StreamContent(tempStream);
foreach(var header in Request.Content.Headers)
{
streamContent.Headers.Add(header.Key, header.Value);
}

// Read the form data and return an async task.
await streamContent.ReadAsMultipartAsync(provider);

并在web.config中添加如下代码

<system.web>
<httpRuntime maxRequestLength="30000000" />
</system.web>

<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="30000000" />
</requestFiltering>
</security>
</system.webServer>

希望这对您有所帮助。

关于c# - 使用 HttpClient 将文件上传到 ASP.NET WebApi 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52025025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com