这不是一个属性,而是压缩 WCF 服务响应的基本代码,如果需要,可以将其包装到一个属性中。
public static void CompressResponseStream(HttpContext context = null)
{
if (context == null)
context = HttpContext.Current;
string encodings = context.Request.Headers.Get("Accept-Encoding");
if (!string.IsNullOrEmpty(encodings))
{
encodings = encodings.ToLowerInvariant();
if (encodings.Contains("deflate"))
{
context.Response.Filter = new DeflateStream(context.Response.Filter, CompressionMode.Compress);
context.Response.AppendHeader("Content-Encoding", "deflate");
context.Response.AppendHeader("X-CompressResponseStream", "deflate");
}
else if (encodings.Contains("gzip"))
{
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
context.Response.AppendHeader("Content-Encoding", "gzip");
context.Response.AppendHeader("X-CompressResponseStream", "gzip");
}
else
{
context.Response.AppendHeader("X-CompressResponseStream", "no-known-accept");
}
}
}
[编辑]解决评论:
只需在 Web 服务操作主体的任何位置调用它,因为它会在响应中设置属性:
[OperationContract]
public ReturnType GetInformation(...) {
// do some stuff
CompressResponseStream();
}