我有一个POST ASP.Net Web Api方法,它改编自ASP.NET Web API RTM异步文件上传指南。
在第一个请求被触发并完成之后,我遇到了所有请求都出现故障的问题。
以下是情况:我有一个示例页面,可以将文件和其他参数一起发布到Web API Post方法。第一次运行正常,文件上传成功。但是,所有后续请求都会导致任务处于出错状态。我得到“意外结束MIME多部分流。MIME多部分消息不完整。”的错误信息。你们有什么想法吗?
下面贴出我的Post方法的源代码、示例html表单和Aggregate Exception。
public Task<HttpResponseMessage> Post([FromUri]string memberNumber)
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception));
}
return Request.CreateResponse(HttpStatusCode.OK, new MyModel());
});
return task;
}
我正在使用类似这样的示例表单来调用此Web API:
<form name="form1" method="post" enctype="multipart/form-data" action="api/claims/asd123" style="margin:auto;width:500px;">
<div>
<label for="HCPracticeNumber">HC Pratice Number:</label>
<input type="text" name="HCPracticeNumber" id="HCPracticeNumber"/>
</div>
<div>
<label for="ServiceDate">Service/Treatment date:</label>
<input type="text" name="ServiceDate" id="ServiceDate"/>
</div>
<div>
<label for="AmountClaimed">Amount Claimed:</label>
<input type="text" name="AmountClaimed" id="AmountClaimed"/>
</div>
<div>
<label for="Image">Image Attachment:</label>
<input name="Image" type="file" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
返回的AggregateException如下所示:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>One or more errors occurred.</ExceptionMessage>
<ExceptionType>System.AggregateException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Unexpected end of MIME multipart stream. MIME multipart message is not complete.
</ExceptionMessage>
<ExceptionType>System.IO.IOException</ExceptionType>
<StackTrace>
at System.Net.Http.Formatting.Parsers.MimeMultipartBodyPartParser.<ParseBuffer>d__0.MoveNext() at System.Net.Http.HttpContentMultipartExtensions.MoveNextPart(MultipartAsyncContext context)
</StackTrace>
</InnerException>
</Error>
更新:
在Filip的博客建议下,我修改了post方法将流位置重置为0,如下所示:
Stream reqStream = Request.Content.ReadAsStreamAsync().Result;
if (reqStream.CanSeek)
{
reqStream.Position = 0;
}
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
t.Exception));
}
return Request.CreateResponse(HttpStatusCode.OK, new MyModel());
});
但是,这段代码非常不稳定。有时候可以工作,而另一些时候却不能。换句话说,它并没有完全解决问题。