我有一个Web Api端点,我目前正在使用它来上传文件。以下是C#的相关摘要:
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider); // Exception thrown here
foreach (var file in provider.Contents)
{
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
// Doing stuff with the file here
}
当我通过Postman
(Chrome扩展程序)进行测试时,上述工作正常。我这样做时,我没有使用Content-Type
标题。正文为form-data
,唯一的输入是附件。
我现在正试图通过PowerShell
发出同样的请求并且正在努力(应该知道我是Web Api和PowerShell的新手)。下面是我正在运行的powershell脚本:
$apiKey=$args[0]
Write-Host "Using API Key: $apiKey"
$fileId=$args[1]
Write-Host "Using File ID: $fileId"
$sourceFile=$args[2]
Write-Host "Using File: $sourceFile"
$baseUrl = "http://localhost:23857/api"
$url = "$baseUrl/file/$fileId/version"
$fileBin = [IO.File]::ReadAllBytes($sourceFile)
$enc = [System.Text.Encoding]::GetEncoding("iso-8859-1")
$fileEnc = $enc.GetString($fileBin)
$boundary = [System.Guid]::NewGuid().ToString()
$LF = "`n"
$bodyLines = (
"--$boundary",
"Content-Disposition: form-data; name=`"file`"; filename=`"TestApp.apk`"",
"Content-Type: application/octet-stream$LF",
$fileEnc,
"--$boundary--$LF"
) -join $LF
try {
Invoke-RestMethod -Uri $url -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -TimeoutSec 120 -Body $bodyLines -Headers @{"ApiKey"=$apiKey}
}
catch [System.Net.WebException] {
Write-Error( "FAILED to reach '$URL': $_" )
throw $_
}
网址成功点击,但行await Request.Content.ReadAsMultipartAsync(provider);
上会抛出异常。异常消息是:
Unexpected end of MIME multipart stream. MIME multipart message is not complete.
关于这个问题的任何想法?
编辑1
我已经使用以下C#代码在到达端点后查看请求内容:
byte[] rawByteArray = await Request.Content.ReadAsByteArrayAsync();
String rawString = System.Text.Encoding.UTF8.GetString(rawByteArray);
(成功)邮递员请求的输出:
------WebKitFormBoundaryBlYhYzAJUyRbTShB
Content-Disposition: form-data; name="file"; filename="TestApp.apk"
Content-Type: application/octet-stream
encoded file data here
来自(失败的)powershell请求的输出:
--f83e62e1-83a7-495c-8152-10d38500da41
Content-Disposition: form-data; name="file"; filename="TestApp.apk"
Content-Type: application/octet-stream
encoded file data here
除了边界分隔符,我在这里看不出任何区别。
编辑2
还没有找到解决方案。我听说如果请求没有以新行结束,有时会抛出此异常。我将此附加到正文(客户端和服务器端)并且没有更改。
任何人都可以看到我的方法有问题吗?