C# 如何压缩 JSON 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19549312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compress JSON responses
提问by Tono Nam
I am using a lot of ajax calls to query the database and I get large text (json) responses. I will like to compress the response.
我使用了很多 ajax 调用来查询数据库,并且得到大文本 (json) 响应。我想压缩响应。
There is a great way of compressing text using javascript in JavaScript implementation of Gzip.
在Gzip 的 JavaScript 实现中,有一种使用 javascript 压缩文本的好方法。
The problem is I want to compress the response on my aspx server and decmpress it with javascript. Therefore I need to run the lzw_encode
function on my asp.net server. Should I I translate that function to C# or there is another way?
问题是我想压缩我的 aspx 服务器上的响应并用 javascript 压缩它。因此我需要lzw_encode
在我的 asp.net 服务器上运行该函数。我应该将该函数转换为 C# 还是有另一种方法?
Using the link above if you dont want to configure IIS or change header you can compress the code on the server with:
如果您不想配置 IIS 或更改标头,请使用上面的链接,您可以使用以下命令压缩服务器上的代码:
C#
C#
public static string Compress(string s)
{
var dict = new Dictionary<string, int>();
char[] data = s.ToArray();
var output = new List<char>();
char currChar;
string phrase = data[0].ToString();
int code = 256;
for (var i = 1; i < data.Length; i++){
currChar = data[i];
var temp = phrase + currChar;
if (dict.ContainsKey(temp))
phrase += currChar;
else
{
if (phrase.Length > 1)
output.Add((char)dict[phrase]);
else
output.Add((char)phrase[0]);
dict[phrase + currChar] = code;
code++;
phrase = currChar.ToString();
}
}
if (phrase.Length > 1)
output.Add((char)dict[phrase]);
else
output.Add((char)phrase[0]);
return new string(output.ToArray());
}
and on the browser you can decompress it with:
在浏览器上,您可以使用以下命令解压缩:
javascript
javascript
// Decompress an LZW-encoded string
function lzw_decode(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i = 1; i < data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
采纳答案by Karl Anderson
Within your server-side response object add a header for GZip, like this:
在您的服务器端响应对象中为 GZip 添加一个标头,如下所示:
Response.AddHeader("Content-Encoding", "gzip");
Also, you can use the GZipStreamclass to compress your content, like this:
此外,您可以使用GZipStream类来压缩您的内容,如下所示:
Response.Filter = new GZipStream(Response.Filter,
CompressionMode.Compress);