我试图使用
将文件发布到我的WebAPI$ curl -F "appName=SomeApp" -F "version=1.0.0.0" -T C:/path/to/a/file.zip http://localhost/api/AppRepo/AddApp
按照此回答https://stackoverflow.com/a/10327789/1421847,我已经能够接受带有选项-F "image=@C:/path/to/a/file.zip"
的文件,并且还可以阅读appName
和version
个参数。但是,在VSTS构建任务https://github.com/Microsoft/vso-agent-tasks/tree/master/Tasks/cURLUploader中使用cURL我必须使用-T
选项接受请求。
到目前为止,我发现它发出了一个http PUT请求,内容不是MimeMultipart。
答案 0 :(得分:0)
我发现使用-T
选项阻止我将其他参数作为HTTP内容发送,因此我在cURL调用中添加了-H "X-App-Name: MyAppName"
和-H "X-App-Version: 1.0.0.0"
以将这些值作为HTTP获取而不是标题。
我处理请求的WebAPI方法现在看起来如下:
public async Task<HttpResponseMessage> PutApp()
{
const string UnexpectedContentOrHeadersMessage = "Expected a zip-file as content and http headers X-App-Name and X-App-Version.";
if (Request.Content.IsFormData() || Request.Content.IsHttpRequestMessageContent() || Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType, UnexpectedContentOrHeadersMessage));
string appName;
IEnumerable<string> appNameValues;
if (Request.Headers.TryGetValues("X-App-Name", out appNameValues))
appName = appNameValues.First();
else
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType, UnexpectedContentOrHeadersMessage));
Version version;
IEnumerable<string> appVersionValues;
if (Request.Headers.TryGetValues("X-App-Version", out appVersionValues))
version = new Version(appVersionValues.First());
else
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType, UnexpectedContentOrHeadersMessage));
return new HttpResponseMessage(HttpStatusCode.OK);
}
要将内容写为二进制数据,我只需做一些标准的IO工作:
var bytes = await httpContent.ReadAsByteArrayAsync();
Guid fileId = Guid.NewGuid();
FileInfo uploadFile = new FileInfo(Path.Combine(Server.MapPath("~/App_Data"), fileId.ToString()));
using (FileStream fileStream = uploadFile.OpenWrite())
{
await fileStream.WriteAsync(bytes, 0, bytes.Length);
}
这是完整的cURL电话:
$ curl --ntlm --user <user>:<password> -H "X-App-Name: <app-name>" -H "X-App-Version: <app-version>" -T c:/path/to/a/file.zip http://localhost/api/AppRepository/PutApp