using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Text;
using System.Threading.Tasks;

public class ChangeBaseHrefMiddleware
{
    RequestDelegate next;
    private readonly IConfiguration configuration;

    public ChangeBaseHrefMiddleware(RequestDelegate next, IConfiguration configuration)
    {
        this.next = next;
        this.configuration = configuration;
    }

    public async Task Invoke(HttpContext context)
    {
        var newContent = string.Empty;

        // Store the "pre-modified" response stream.
        var existingBody = context.Response.Body;

        using (var newBody = new MemoryStream())
        {
            context.Response.Body = newBody;

            await this.next(context);

            // Set the stream back to the original.
            context.Response.Body = existingBody;

            newBody.Seek(0, SeekOrigin.Begin);

            // newContent will be `Hello`.
            newContent = new StreamReader(newBody).ReadToEnd();

            var isHtml = context.Response.ContentType != null && context.Response.ContentType.ToLower().Contains("text/html");
            if (isHtml)
            {
                newContent = newContent.Replace(@"<base href=""/"">", $@"<base href=""{this.configuration["applicationUri"]}"" >");
                var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
                context.Response.ContentLength = encoding.GetByteCount(newContent);
            }

            // Send our modified content to the response body.
            await context.Response.WriteAsync(newContent);
        }
    }
}