0

I am trying to change the body of specified requested files using code below. The index.html file is correctly sended to client, but other files included in head section are empty on client's side (files are shown in sources tab in chrome). Kestrel do not report any errors. Could you explain me why?

public static Func<HttpContext, Func<Task>, Task> Rewrite()
{
    return async (context, next) =>
    {
        if (context.Request.Path.Value == "/")
        {
            var originalStream = context.Response.Body;

            using (Stream bufferStream = new FileStream("./wwwroot/index.html", FileMode.Open, FileAccess.Read))
            {
                context.Response.Body = bufferStream;
                bufferStream.Seek(0, SeekOrigin.Begin);

                using (var reader = new StreamReader(bufferStream))
                {
                    var response = await reader.ReadToEndAsync();
                    response = response.Replace("[ddd]", "<script type=\"text/javascript\" src=\"lib/jquery/dist/jquery.js\"></script>");

                    using (var writer = new StreamWriter(originalStream))
                    {
                        await writer.WriteAsync(response);
                    }
                }
            }
        }
        else
        {
            await next();
        }
    };
}

Of course this function is registered in configuration file

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(ResponseStreamRewriter.Rewrite());
}
Booma
  • 261
  • 6
  • 19
Adam Mrozek
  • 1,410
  • 4
  • 26
  • 49
  • _"other files included in head section are empty on client's side"_ - which middleware responds to those requests, and with what result? – CodeCaster Apr 26 '18 at 08:37
  • Is there a reason why you don't do that in a razor page? (Home/Index being the default route (unless set otherwise), when just `/` has been requested) – Tseng Apr 26 '18 at 10:56
  • @Tseng There is no reason, but I will be using websockets so I can't load different page without closing websocket session, but maybe razor page for index only is not a bad idea.. However I think that way is more readable for me. – Adam Mrozek Apr 26 '18 at 11:02
  • @CodeCaster standard one, this example should modify only index.html. Other files are handled in standard way – Adam Mrozek Apr 26 '18 at 12:10

0 Answers0