我怎么知道Task.Isfaulted为什么是真的?

时间:2019-01-30 09:36:54

标签: c# asp.net-mvc api post

我正在关注this博客。我想创建将接受文件的post方法。

[HttpPost]
        public Task<IEnumerable<FileDescDto>> Post()
        {
            var folderName = "Uploads";
            var PATH = HttpContext.Current.Server.MapPath("~/" + folderName);
            var rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);
            if (Request.Content.IsMimeMultipartContent())
            {
                var streamProvider = new CustomMultipartFormDataStreamProvider(PATH);
                var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDescDto>>(t =>
                {

                    if (t.IsFaulted || t.IsCanceled)
                    {
                       throw new HttpResponseException(HttpStatusCode.InternalServerError);
                    }

                    var fileInfo = streamProvider.FileData.Select(i => {
                        var info = new FileInfo(i.LocalFileName);
                        return new FileDescDto(info.Name, rootUrl + "/" + folderName + "/" + info.Name, info.Length / 1024);
                    });
                    return fileInfo;
                });

                return task;
            }

            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
        }
    }

当我调试时,我得到t.IsFaulted为true,并且无法上传。 如何查看为什么失败以及如何解决?

1 个答案:

答案 0 :(得分:6)

如果Task出现故障,theTask.Exception会向您确切显示发生了什么,但是坦率地说,简单地await theTask和使用它会更容易很多常规异常处理。 ContinueWith是一项旧功能(请参阅Filder指出的4.0免责声明),并且很少在新代码中使用。整个方法很容易async