|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +// Based on https://github.com/RickStrahl/Westwind.AspnetCore.LiveReload/blob/128b5f524e86954e997f2c453e7e5c1dcc3db746/Westwind.AspnetCore.LiveReload/ResponseStreamWrapper.cs |
| 5 | + |
| 6 | +using System; |
| 7 | +using System.IO; |
| 8 | +using System.Threading; |
| 9 | +using System.Threading.Tasks; |
| 10 | +using Microsoft.AspNetCore.Http; |
| 11 | +using Microsoft.Extensions.Logging; |
| 12 | +using Microsoft.Net.Http.Headers; |
| 13 | + |
| 14 | +namespace Microsoft.AspNetCore.Watch.BrowserRefresh |
| 15 | +{ |
| 16 | + /// <summary> |
| 17 | + /// Wraps the Response Stream to inject the WebSocket HTML into |
| 18 | + /// an HTML Page. |
| 19 | + /// </summary> |
| 20 | + public class ResponseStreamWrapper : Stream |
| 21 | + { |
| 22 | + private static readonly MediaTypeHeaderValue _textHtmlMediaType = new MediaTypeHeaderValue("text/html"); |
| 23 | + private readonly Stream _baseStream; |
| 24 | + private readonly HttpContext _context; |
| 25 | + private readonly ILogger _logger; |
| 26 | + private bool? _isHtmlResponse; |
| 27 | + |
| 28 | + public ResponseStreamWrapper(HttpContext context, ILogger logger) |
| 29 | + { |
| 30 | + _context = context; |
| 31 | + _baseStream = context.Response.Body; |
| 32 | + _logger = logger; |
| 33 | + } |
| 34 | + |
| 35 | + public override bool CanRead => false; |
| 36 | + public override bool CanSeek => false; |
| 37 | + public override bool CanWrite => true; |
| 38 | + public override long Length { get; } |
| 39 | + public override long Position { get; set; } |
| 40 | + public bool ScriptInjectionPerformed { get; private set; } |
| 41 | + |
| 42 | + public bool IsHtmlResponse => _isHtmlResponse ?? false; |
| 43 | + |
| 44 | + public override void Flush() |
| 45 | + { |
| 46 | + OnWrite(); |
| 47 | + _baseStream.Flush(); |
| 48 | + } |
| 49 | + |
| 50 | + public override Task FlushAsync(CancellationToken cancellationToken) |
| 51 | + { |
| 52 | + OnWrite(); |
| 53 | + return _baseStream.FlushAsync(cancellationToken); |
| 54 | + } |
| 55 | + |
| 56 | + public override void Write(ReadOnlySpan<byte> buffer) |
| 57 | + { |
| 58 | + OnWrite(); |
| 59 | + if (IsHtmlResponse && !ScriptInjectionPerformed) |
| 60 | + { |
| 61 | + ScriptInjectionPerformed = WebSocketScriptInjection.TryInjectLiveReloadScript(_baseStream, buffer); |
| 62 | + } |
| 63 | + else |
| 64 | + { |
| 65 | + _baseStream.Write(buffer); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + public override void WriteByte(byte value) |
| 70 | + { |
| 71 | + OnWrite(); |
| 72 | + _baseStream.WriteByte(value); |
| 73 | + } |
| 74 | + |
| 75 | + public override void Write(byte[] buffer, int offset, int count) |
| 76 | + { |
| 77 | + OnWrite(); |
| 78 | + |
| 79 | + if (IsHtmlResponse && !ScriptInjectionPerformed) |
| 80 | + { |
| 81 | + ScriptInjectionPerformed = WebSocketScriptInjection.TryInjectLiveReloadScript(_baseStream, buffer.AsSpan(offset, count)); |
| 82 | + } |
| 83 | + else |
| 84 | + { |
| 85 | + _baseStream.Write(buffer, offset, count); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| 90 | + { |
| 91 | + OnWrite(); |
| 92 | + |
| 93 | + if (IsHtmlResponse && !ScriptInjectionPerformed) |
| 94 | + { |
| 95 | + ScriptInjectionPerformed = await WebSocketScriptInjection.TryInjectLiveReloadScriptAsync(_baseStream, buffer.AsMemory(offset, count), cancellationToken); |
| 96 | + } |
| 97 | + else |
| 98 | + { |
| 99 | + await _baseStream.WriteAsync(buffer, offset, count, cancellationToken); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) |
| 104 | + { |
| 105 | + OnWrite(); |
| 106 | + |
| 107 | + if (IsHtmlResponse && !ScriptInjectionPerformed) |
| 108 | + { |
| 109 | + ScriptInjectionPerformed = await WebSocketScriptInjection.TryInjectLiveReloadScriptAsync(_baseStream, buffer, cancellationToken); |
| 110 | + } |
| 111 | + else |
| 112 | + { |
| 113 | + await _baseStream.WriteAsync(buffer, cancellationToken); |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + private void OnWrite() |
| 118 | + { |
| 119 | + if (_isHtmlResponse.HasValue) |
| 120 | + { |
| 121 | + return; |
| 122 | + } |
| 123 | + |
| 124 | + var response = _context.Response; |
| 125 | + |
| 126 | + _isHtmlResponse = |
| 127 | + (response.StatusCode == StatusCodes.Status200OK || response.StatusCode == StatusCodes.Status500InternalServerError) && |
| 128 | + MediaTypeHeaderValue.TryParse(response.ContentType, out var mediaType) && |
| 129 | + mediaType.IsSubsetOf(_textHtmlMediaType) && |
| 130 | + (!mediaType.Charset.HasValue || mediaType.Charset.Equals("utf-8", StringComparison.OrdinalIgnoreCase)); |
| 131 | + |
| 132 | + if (_isHtmlResponse.Value) |
| 133 | + { |
| 134 | + BrowserRefreshMiddleware.Log.SetupResponseForBrowserRefresh(_logger); |
| 135 | + |
| 136 | + // Since we're changing the markup content, reset the content-length |
| 137 | + response.Headers.ContentLength = null; |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); |
| 142 | + |
| 143 | + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); |
| 144 | + |
| 145 | + public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| 146 | + => throw new NotSupportedException(); |
| 147 | + |
| 148 | + public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) |
| 149 | + => throw new NotSupportedException(); |
| 150 | + |
| 151 | + public override void SetLength(long value) => throw new NotSupportedException(); |
| 152 | + } |
| 153 | +} |
0 commit comments