Skip to main content
 首页 » 编程设计

c#之如何减少 WCF soap 消息大小以节省带宽

2024年02月20日22myhome

我编写了一个 MessageSizeInspector 类来检查服务从客户端接收的消息的大小。这是它的样子:

//the actual implementation logs more! 
//but in this question, my only concerns is request.ToString() 
public sealed class MessageSizeInspector :  
            BehaviorExtensionElement,   //to enable it to be used in config 
            IDispatchMessageInspector,  //service-side inspector 
            IEndpointBehavior           //so we can apply it on endpoint 
{ 
   if (request != null ) 
   { 
      Logger.Verbose("Message = {0}\n", request.ToString())); 
   }        
   //more   
} 

它记录这种格式的消息:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> 
  <s:Header> 
    <To s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://localhost:8961/EngineService</To> 
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IEngineService/GetMousePatternID</Action> 
  </s:Header> 
  <s:Body> 
    <GetMousePatternID xmlns="http://tempuri.org/"> 
      <args> 
        <accelerator xmlns="http://schemas.datacontract.org/2004/07/Runaware.Insight.EngineService" /> 
        <accessKey xmlns="http://schemas.datacontract.org/2004/07/Runaware.Insight.EngineService" /> 
        <controlId xmlns="http://schemas.datacontract.org/2004/07/Runaware.Insight.EngineService">66222</controlId> 
 
        <!--- deleted the rest to avoid verbosity --> 
 
      </args> 
    </GetMousePatternID> 
  </s:Body> 
</s:Envelope> 

如您所见,实际消息很小,但 XML 元素和命名空间使其太大。与实际消息相比,命名空间尤其太大。

我的问题是:我们如何才能减小soap 消息的大小?由于所有元素的 xmlns 都相同,WCF 可以对此进行优化,但事实并非如此。我们可以让它使用我们选择的更短的命名空间吗?有一些元素,例如 accelerator 和 accessKey 甚至没有任何值(您可以通过向右滚动看到),但它们仍然存在!我们能否让 WCF 忽略它们并在服务端假定它们的值为 null(或默认值)?

简而言之,我们可以做些什么来节省带宽?

我假设上面的消息是来自客户端的消息,格式完全相同,具有相同的 XML 元素和命名空间。

服务器是用C#和WCF写的,客户端是用C++写的Windows Web Services API .服务和客户端都是我写的。所以我可以完全控制它们。如果需要,我可能会更改它以节省带宽!

请您参考如下方法:

除了其他人已经说过的答案(例如:WCF 压缩)...

尝试在 DataContracts、DataMembers 和 ServiceContracts 上设置名称和命名空间。

例子:

 [DataContract(Name = "a", Namespace = "")] 
 class Person 
 { 
     [DataMember(Name = "a")] 
     public string FullName; 
     [DataMember(Name = "b)] 
     public int Age; 
 } 

这将使 Person 从命名空间“”中被称为“a”,并且属性 FullName 被称为“a”,使 XML 更短,如:

<a> -- Represents the Person class 
    <a>Name of the person</a> -- Represents the FullName property 
    <b>38</b> 
</a> 

属性和类必须具有不同于 DataContract 和 DataMembers 的“短”名称。

引用:https://bkiener.wordpress.com/2010/05/04/optimize-data-contracts-for-better-wcf-performance/