-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathResponseStreamWrapper.cs
149 lines (123 loc) · 5.31 KB
/
ResponseStreamWrapper.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Based on https://github.com/RickStrahl/Westwind.AspnetCore.LiveReload/blob/128b5f524e86954e997f2c453e7e5c1dcc3db746/Westwind.AspnetCore.LiveReload/ResponseStreamWrapper.cs
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Watch.BrowserRefresh
{
/// <summary>
/// Wraps the Response Stream to inject the WebSocket HTML into
/// an HTML Page.
/// </summary>
public class ResponseStreamWrapper : Stream
{
private static readonly MediaTypeHeaderValue _textHtmlMediaType = new("text/html");
private readonly Stream _baseStream;
private readonly HttpContext _context;
private readonly ILogger _logger;
private bool? _isHtmlResponse;
public ResponseStreamWrapper(HttpContext context, ILogger logger)
{
_context = context;
_baseStream = context.Response.Body;
_logger = logger;
}
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length { get; }
public override long Position { get; set; }
public bool ScriptInjectionPerformed { get; private set; }
public bool IsHtmlResponse => _isHtmlResponse ?? false;
public override void Flush()
{
OnWrite();
_baseStream.Flush();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
OnWrite();
return _baseStream.FlushAsync(cancellationToken);
}
public override void Write(ReadOnlySpan<byte> buffer)
{
OnWrite();
if (IsHtmlResponse && !ScriptInjectionPerformed)
{
ScriptInjectionPerformed = WebSocketScriptInjection.TryInjectLiveReloadScript(_baseStream, buffer);
}
else
{
_baseStream.Write(buffer);
}
}
public override void WriteByte(byte value)
{
OnWrite();
_baseStream.WriteByte(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
OnWrite();
if (IsHtmlResponse && !ScriptInjectionPerformed)
{
ScriptInjectionPerformed = WebSocketScriptInjection.TryInjectLiveReloadScript(_baseStream, buffer.AsSpan(offset, count));
}
else
{
_baseStream.Write(buffer, offset, count);
}
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
OnWrite();
if (IsHtmlResponse && !ScriptInjectionPerformed)
{
ScriptInjectionPerformed = await WebSocketScriptInjection.TryInjectLiveReloadScriptAsync(_baseStream, buffer.AsMemory(offset, count), cancellationToken);
}
else
{
await _baseStream.WriteAsync(buffer, offset, count, cancellationToken);
}
}
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
OnWrite();
if (IsHtmlResponse && !ScriptInjectionPerformed)
{
ScriptInjectionPerformed = await WebSocketScriptInjection.TryInjectLiveReloadScriptAsync(_baseStream, buffer, cancellationToken);
}
else
{
await _baseStream.WriteAsync(buffer, cancellationToken);
}
}
private void OnWrite()
{
if (_isHtmlResponse.HasValue)
{
return;
}
var response = _context.Response;
_isHtmlResponse =
(response.StatusCode == StatusCodes.Status200OK || response.StatusCode == StatusCodes.Status500InternalServerError) &&
MediaTypeHeaderValue.TryParse(response.ContentType, out var mediaType) &&
mediaType.IsSubsetOf(_textHtmlMediaType) &&
(!mediaType.Charset.HasValue || mediaType.Charset.Equals("utf-8", StringComparison.OrdinalIgnoreCase));
if (_isHtmlResponse.Value)
{
BrowserRefreshMiddleware.Log.SetupResponseForBrowserRefresh(_logger);
// Since we're changing the markup content, reset the content-length
response.Headers.ContentLength = null;
}
}
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
=> throw new NotSupportedException();
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
=> throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
}
}