I am writing a proxy for some site using ASP.NET Core 2.0. My proxy works fine if all it does is just re-translating HttpResponseMessage
to the browser. My proxy based on this example. But I need to make some changes site content, for instance, some of the href contains an absolute reference. So when I click them from my proxy, I get to the original site, and it is a problem.
When I tried to get site HTML as a string, I got only special characters. After some search, I find this solution. It fits for my case well and I successfully get site content as a string, which starts with "<!DOCTYPE html>..."
. After changes are done I need to send this string to my browser, and here I have a problem. I work with the HttpResponseMessage
the following way:
using (var responseStream = await responseMessage.Content.ReadAsStreamAsync())
{
string str;
using (var gZipStream = new GZipStream(responseStream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gZipStream))
{
str = await streamReader.ReadToEndAsync();
//some stings changes...
}
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gZipStream = new GZipStream(mso, CompressionMode.Compress))
{
await msi.CopyToAsync(gZipStream);
await gZipStream.CopyToAsync(response.Body, StreamCopyBufferSize, context.RequestAborted);
}
}
//next string works, but I don't change content this way
//await responseStream.CopyToAsync(response.Body, StreamCopyBufferSize, context.RequestAborted);
}
I create GZipStream
, successfully copy MemoryStream
into it, then I want to copy GZipStream
into a response.Body
(HttpResponse
) using CopyToAsync
. On that line I get `NotSupportedException' with message
GZipStream does not support reading
I find out, after compression into GZipStream
gZipStream.CanRead
is false
for some reason. I tried to copy msi
into response.Body
, it doesn't throw exceptions, but in the browser, I get an empty page (document Response in Network in browser console is also empty).
Hope someone will be able to tell me, that I am doing wrong.