如何在C#中使用互操作性实现WCF RESTful(JSON)服务的压缩?

时间:2013-06-18 21:55:50

标签: json wcf rest interop compression

我有一个用C#构建的WCF RESTful(即JSON)服务。其中一个DataContract方法可以返回非常大的响应,最小10 MB,最大可能超过30 MB。它是所有文本,并将其作为JSON数据返回给客户端。当我在浏览器中测试这个方法时,我看到它超时了。我知道有一种方法可以压缩WCF RESTful服务响应数据。由于互操作性对我的目的绝对至关重要,是否仍然可以压缩WCF RESTful服务响应数据?现在,我还在本地机器上测试项目。不过,我将把它部署到IIS。

如果有一种方法可以通过互操作性进行压缩,那么如何实现呢?

谢谢。

这实际上不是我正在使用的文件集,但它只是展示我如何构建服务的示例。我意识到这个样本根本不需要压缩。

IService1.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService4
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(
            Method = "GET", 
            UriTemplate = "employees",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare)]
        List<Employee> GetEmployees();
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class Employee
    {
        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }

        [DataMember]
        public int Age { get; set; }

        public Employee(string firstName, string lastName, int age)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Age = age;
        }
    }
}

Service1.svc.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Net;

namespace WcfService4
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        public List<Employee> GetEmployees()
        {
            // In reality, I'm calling the data from an external datasource, returning data to the client that exceeds 10 MB and can reach an upper limit of at least 30 MB.               

            List<Employee> employee = new List<Employee>();
            employee.Add(new Employee("John", "Smith", 28));
            employee.Add(new Employee("Jane", "Fonda", 42));
            employee.Add(new Employee("Brett", "Hume", 56));

            return employee;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您可以更改web.config文件以解决此问题。 改变httpRuntime

<httpRuntime maxRequestLength="10240" executionTimeout="1000" />

这里,

maxRequestLength:表示ASP.NET支持的最大文件上载大小。此限制可用于防止用户将大文件发布到服务器而导致的拒绝服务攻击。指定的大小以千字节为单位。默认值为4096 KB(4 MB)。

executionTimeout:表示在ASP.NET自动关闭之前允许执行请求的最大秒数。