我发现使用该-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