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
|
public class CompressionExtension : System.Web.Services.Protocols.SoapExtension
{
Stream oldStream;
Stream newStream;
public override Stream ChainStream(Stream stream)
{
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
public override object GetInitializer(Type serviceType)
{
return typeof(CompressionExtension);
}
public override object GetInitializer(System.Web.Services.Protocols.LogicalMethodInfo methodInfo, System.Web.Services.Protocols.SoapExtensionAttribute attribute)
{
return attribute;
}
public override void Initialize(object initializer)
{
return;
}
public override void ProcessMessage(System.Web.Services.Protocols.SoapMessage message)
{
switch (message.Stage)
{
case System.Web.Services.Protocols.SoapMessageStage.AfterDeserialize:
break;
case System.Web.Services.Protocols.SoapMessageStage.AfterSerialize:
Zip(message.Stream);
break;
case System.Web.Services.Protocols.SoapMessageStage.BeforeDeserialize:
Unzip(message.Stream);
break;
case System.Web.Services.Protocols.SoapMessageStage.BeforeSerialize:
message.ContentEncoding = "gzip";
break;
default:
throw new Exception("invalid stage");
break;
}
}
private void Unzip(Stream message)
{
MemoryStream ms = new MemoryStream();
ms.Position = 0;
message.Position = 0;
GZipInputStream zip = new GZipInputStream(message);
byte[] data = new byte[1024];
int offset = 0;
while ((offset = zip.Read(data, 0, data.Length)) > 0)
{
ms.Write(data, 0, offset);
}
ms.Flush();
ms.Position = 0;
Copy(ms, newStream);
zip.Close();
}
private void Zip(Stream message)
{
message.Position = 0;
MemoryStream ms = new MemoryStream();
ms.Position = 0;
message.Position = 0;
GZipOutputStream zip = new GZipOutputStream(ms);
byte[] data = new byte[1024];
int offset = 0;
while ((offset = message.Read(data, 0, data.Length)) > 0)
{
zip.Write(data, 0, offset);
}
zip.Finish();
ms.Position = 0;
Copy(ms, oldStream);
zip.Close();
}
void Copy(Stream from, Stream to)
{
byte[] data = new byte[1024];
int offset = 0;
while ((offset = from.Read(data, 0, data.Length)) != 0)
{
to.Write(data, 0, offset);
}
to.Flush();
}
} |
Partager