gpt4 book ai didi

asp.net - ASP.NET Web API 完成向客户端发送时是否有通知

转载 作者:行者123 更新时间:2023-12-04 14:47:19 25 4
gpt4 key购买 nike

我正在使用 Web API 将大文件流式传输到客户端,但我想记录下载是否成功。也就是说,如果服务器发送了文件的全部内容。

有什么方法可以在 HttpResponseMessage 时获得回调或事件完成发送数据?

也许是这样的:

var stream = GetMyStream();
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
// This doesn't exist, but it illustrates what I'm trying to do.
response.OnComplete(context =>
{
if (context.Success)
Log.Info("File downloaded successfully.");
else
Log.Warn("File download was terminated by client.");
});

最佳答案

编辑:我现在已经使用真实连接(通过 fiddler )对此进行了测试。

我继承了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;

关于asp.net - ASP.NET Web API 完成向客户端发送时是否有通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13963591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com