編輯:我現在一直在使用一個真正的連接(通過小提琴手)測試此。
我繼承StreamContent
,並加入我自己的OnComplete
行動,檢查了異常:
public class StreamContentWithCompletion : StreamContent
{
public StreamContentWithCompletion(Stream stream) : base (stream) { }
public StreamContentWithCompletion(Stream stream, Action<Exception> onComplete) : base(stream)
{
this.OnComplete = onComplete;
}
public Action<Exception> OnComplete { get; set; }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
var t = base.SerializeToStreamAsync(stream, context);
t.ContinueWith(x =>
{
if (this.OnComplete != null)
{
// The task will be in a faulted state if something went wrong.
// I observed the following exception when I aborted the fiddler session:
// 'System.Web.HttpException (0x800704CD): The remote host closed the connection.'
if (x.IsFaulted)
this.OnComplete(x.Exception.GetBaseException());
else
this.OnComplete(null);
}
}, TaskContinuationOptions.ExecuteSynchronously);
return t;
}
}
然後我用它像這樣:
var stream = GetMyStream();
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContentWithCompletion(stream, ex =>
{
if (ex == null)
Log.Info("File downloaded successfully.");
else
Log.Warn("File download was terminated by client.");
});
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
我不確定在我使用'ApiController'操作方法時,這對我有用。據我所知,在我返回'HttpResponseMessage'之前什麼也沒有發生。 – ligos
@ligos你可以做一個測試嗎? - 我喜歡說你的另一個,你可以用緩衝區在一個小部分的循環中寫入數據,並檢查最終下載是否與文件大小相同? – Aristos
是的,明天我會進行測試。哦,客戶端無論如何都會有可用的SHA256散列,所以我得到了文件完整性。 – ligos