我有一个 POST ASP.Net Web Api 方法,改编自A guide to asynchronous file uploads in ASP.NET Web API RTM。
我遇到了第一个请求被触发并完成后触发的所有请求的错误任务问题。
场景如下:我有一个示例页面,该页面将文件连同其他参数一起发布到 Web API Post 方法。第一次运行良好,文件已上传。但是,所有后续请求最终都会使任务处于故障状态。我收到“MIME 多部分流意外结束。MIME 多部分消息不完整。” 任何想法为什么?
下面粘贴的是我的 Post 方法、示例 html 表单和聚合异常的源代码。
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());
});
但是,这是非常喜怒无常的代码。它有时有效,但有时无效。换句话说,它并不能完全解决问题。