/
StreamContent.cs
178 lines (146 loc) · 6.86 KB
/
StreamContent.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public class StreamContent : HttpContent
{
private Stream _content;
private int _bufferSize;
private bool _contentConsumed;
private long _start;
public StreamContent(Stream content)
{
ArgumentNullException.ThrowIfNull(content);
// Indicate that we should use default buffer size by setting size to 0.
InitializeContent(content, 0);
}
public StreamContent(Stream content, int bufferSize)
{
ArgumentNullException.ThrowIfNull(content);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize);
InitializeContent(content, bufferSize);
}
[MemberNotNull(nameof(_content))]
private void InitializeContent(Stream content, int bufferSize)
{
_content = content;
_bufferSize = bufferSize;
if (content.CanSeek)
{
_start = content.Position;
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Associate(this, content);
}
protected override void SerializeToStream(Stream stream, TransportContext? context, CancellationToken cancellationToken)
{
Debug.Assert(stream != null);
PrepareContent();
// If the stream can't be re-read, make sure that it gets disposed once it is consumed.
StreamToStreamCopy.Copy(_content, stream, _bufferSize, !_content.CanSeek);
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) =>
SerializeToStreamAsyncCore(stream, default);
protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) =>
// Only skip the original protected virtual SerializeToStreamAsync if this
// isn't a derived type that may have overridden the behavior.
GetType() == typeof(StreamContent) ? SerializeToStreamAsyncCore(stream, cancellationToken) :
base.SerializeToStreamAsync(stream, context, cancellationToken);
private Task SerializeToStreamAsyncCore(Stream stream, CancellationToken cancellationToken)
{
Debug.Assert(stream != null);
PrepareContent();
return StreamToStreamCopy.CopyAsync(
_content,
stream,
_bufferSize,
!_content.CanSeek, // If the stream can't be re-read, make sure that it gets disposed once it is consumed.
cancellationToken);
}
protected internal override bool TryComputeLength(out long length)
{
if (_content.CanSeek)
{
length = _content.Length - _start;
return true;
}
else
{
length = 0;
return false;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_content.Dispose();
}
base.Dispose(disposing);
}
protected override Stream CreateContentReadStream(CancellationToken cancellationToken) =>
new ReadOnlyStream(_content);
protected override Task<Stream> CreateContentReadStreamAsync()
{
// Wrap the stream with a read-only stream to prevent someone from writing to the stream.
return Task.FromResult<Stream>(new ReadOnlyStream(_content));
}
internal override Stream? TryCreateContentReadStream() =>
GetType() == typeof(StreamContent) ? new ReadOnlyStream(_content) : // type check ensures we use possible derived type's CreateContentReadStreamAsync override
null;
internal override bool AllowDuplex => false;
private void PrepareContent()
{
if (_contentConsumed)
{
// If the content needs to be written to a target stream a 2nd time, then the stream must support
// seeking (e.g. a FileStream), otherwise the stream can't be copied a second time to a target
// stream (e.g. a NetworkStream).
if (_content.CanSeek)
{
_content.Position = _start;
}
else
{
throw new InvalidOperationException(SR.net_http_content_stream_already_read);
}
}
_contentConsumed = true;
}
private sealed class ReadOnlyStream : DelegatingStream
{
public ReadOnlyStream(Stream innerStream) : base(innerStream)
{
}
public override bool CanWrite => false;
public override void Flush() { }
public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public override void SetLength(long value) =>
throw new NotSupportedException(SR.net_http_content_readonly_stream);
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) =>
throw new NotSupportedException(SR.net_http_content_readonly_stream);
public override void EndWrite(IAsyncResult asyncResult) =>
throw new NotSupportedException(SR.net_http_content_readonly_stream);
public override void Write(byte[] buffer, int offset, int count) =>
throw new NotSupportedException(SR.net_http_content_readonly_stream);
public override void Write(ReadOnlySpan<byte> buffer) =>
throw new NotSupportedException(SR.net_http_content_readonly_stream);
public override void WriteByte(byte value) =>
throw new NotSupportedException(SR.net_http_content_readonly_stream);
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
throw new NotSupportedException(SR.net_http_content_readonly_stream);
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) =>
throw new NotSupportedException(SR.net_http_content_readonly_stream);
public override int WriteTimeout
{
get => throw new InvalidOperationException(SR.net_http_content_readonly_stream);
set => throw new InvalidOperationException(SR.net_http_content_readonly_stream);
}
}
}
}