1

在我的服务合同中,我公开了一个将Stream作为参数的方法:

[OperationContract]
[WebInvoke(UriTemplate = "/Upload?fileName={fileName}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Stream Upload(String fileName, Stream fileData);

当我这样做时,我的自定义 WebServiceHost 实现(从自定义 WebServiceHostFactory 实现实例化)将端点绑定视为 CustomBinding 而不是 WebHttpBinding:

public class myWebServiceHost : WebServiceHost {
  .
  .
  .
  protected override void OnOpening() {
    base.OnOpening();
    if (base.Description != null) {
      foreach (ServiceEndpoint endpoint in base.Description.Endpoints) {
        WebHttpBinding binding = endpoint.Binding as WebHttpBinding;
        if (binding != null) { //Will always be null given the operation contract above
          Int32 MB = 1048576 * Convert.ToInt32(ConfigurationManager.AppSettings["requestSizeMax"]);
          binding.MaxReceivedMessageSize = MB;
          binding.TransferMode = TransferMode.Streamed;
        }
      }
    }
  }
}

这是一个问题,因为我需要上传大于 64KB 的文件......关于如何为 CustomBinding 设置 MaxReceivedMessageSize 或如何确保我的 Binding 设置为 WebHttpBinding 的任何想法。

PS 我需要以编程方式执行此操作,因此 .config 设置对我没有任何用处。

4

1 回答 1

2

好的,所以在深入研究了这个之后,这就是我想出的:

protected override void OnOpening() {
  base.OnOpening();
  if (base.Description != null) {
    foreach (ServiceEndpoint endpoint in base.Description.Endpoints) {
      Int32 MB = 1048576 * Convert.ToInt32(ConfigurationManager.AppSettings["requestSizeMax"]);
      switch(endpoint.Binding.GetType().ToString()) {
        case "System.ServiceModel.Channels.CustomBinding":
          CustomBinding custom = (CustomBinding)endpoint.Binding;
          custom.Elements.Find<HttpTransportBindingElement>().MaxReceivedMessageSize = MB;
          custom.Elements.Find<HttpTransportBindingElement>().TransferMode = TransferMode.Streamed;
        break;
        case "System.ServiceModel.WebHttpBinding":
          WebHttpBinding webhttp = (WebHttpBinding)endpoint.Binding;
          webhttp.MaxReceivedMessageSize = MB;
          webhttp.TransferMode = TransferMode.Streamed;
        break;
      }
    }
  }
}

它有效,尽管它绝对可以改进。我仍然需要看看是否有更通用的方法来处理这个问题,而不是按类型分离案例。虽然目前我没有看到任何其他方法(因为绑定类型基于服务本身的方法,请记住,当我将 Stream 参数添加到服务方法之一时,它才从 WebHttpBinding 切换到 CustomBinding )。

  • 如果有人对此主题有任何其他见解,请发表。
于 2014-01-10T18:42:39.823 回答