// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http.Handlers
{
///
/// The provides a mechanism for getting progress event notifications
/// when sending and receiving data in connection with exchanging HTTP requests and responses.
/// Register event handlers for the events and
/// to see events for data being sent and received.
///
public class ProgressMessageHandler : DelegatingHandler
{
///
/// Initializes a new instance of the class.
///
public ProgressMessageHandler()
{
}
///
/// Initializes a new instance of the class.
///
/// The inner handler to which this handler submits requests.
public ProgressMessageHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{
}
///
/// Occurs every time the client sending data is making progress.
///
public event EventHandler HttpSendProgress;
///
/// Occurs every time the client receiving data is making progress.
///
public event EventHandler HttpReceiveProgress;
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
AddRequestProgress(request);
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
if (HttpReceiveProgress != null && response != null && response.Content != null)
{
cancellationToken.ThrowIfCancellationRequested();
await AddResponseProgressAsync(request, response);
}
return response;
}
///
/// Raises the event.
///
/// The request.
/// The instance containing the event data.
protected internal virtual void OnHttpRequestProgress(HttpRequestMessage request, HttpProgressEventArgs e)
{
if (HttpSendProgress != null)
{
HttpSendProgress(request, e);
}
}
///
/// Raises the event.
///
/// The request.
/// The instance containing the event data.
protected internal virtual void OnHttpResponseProgress(HttpRequestMessage request, HttpProgressEventArgs e)
{
if (HttpReceiveProgress != null)
{
HttpReceiveProgress(request, e);
}
}
private void AddRequestProgress(HttpRequestMessage request)
{
if (HttpSendProgress != null && request != null && request.Content != null)
{
HttpContent progressContent = new ProgressContent(request.Content, this, request);
request.Content = progressContent;
}
}
private async Task AddResponseProgressAsync(HttpRequestMessage request, HttpResponseMessage response)
{
Stream stream = await response.Content.ReadAsStreamAsync();
ProgressStream progressStream = new ProgressStream(stream, this, request, response);
HttpContent progressContent = new StreamContent(progressStream);
response.Content.Headers.CopyTo(progressContent.Headers);
response.Content = progressContent;
return response;
}
}
}