1

我想利用WebScriptEnablingBehavior我的 WCF REST 服务来提供生成 javascript 客户端代理(以及随之而来的强类型对象)的能力。
它适用于GETandclient.DownloadData()方法(作为查询字符串传递的参数),但我正在努力让它与POSTand一起使用client.UploadData(...)

问题是我的服务方法中的参数最终都为空(没有错误/异常,我可以通过它进行调试......它们只是空的)。

web.config文件_

<services>
  <service behaviorConfiguration="ServiceBehavior" name="ServWS_Main_2.WS_Main_2">
    <endpoint address="" behaviorConfiguration="JSONOnly" binding="webHttpBinding"
      bindingConfiguration="StreamedRequestWebBinding" contract="ServWS_Main_2.IServWS" />
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="JSONOnly">
      <enableWebScript/>
    </behavior>
  </endpointBehaviors>
</behaviors>

服务合同

[ServiceContract]
public interface IServWS
{
    [OperationContract]
    [WebInvoke(Method = "POST")]
    ProviderInfo AddTo(string serviceName, BubbleInfo bubble);
}

实施

public class WS_Main_2 : IServWS
{
    public ProviderInfo AddTo(string serviceName, BubbleInfo bubble)
    {
        // at this point both serviceName and bubble  are null
    }
}

作为参数传递的复杂类型的定义

[DataContract]
public class BubbleInfo
{

    [DataMember(EmitDefaultValue = false)]
    public string Text { get; set; }

    [DataMember(EmitDefaultValue = false)]
    public string Caption { get; set; }
}

来自客户的电话

BubbleInfo bub = new BubbleInfo() { Text = "test2" };

MemoryStream stream = new MemoryStream();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(BubbleInfo));
serializer.WriteObject(stream, bub);

var url = GetURL() + "/addto?serviceName=MyService";
byte[] data = client.UploadData(url, "POST", stream.ToArray());

请注意,如果我不使用WebScriptEnablingBehaviorbutwebHttpURITemplate代替,它可以正常工作。
使用 Visual Studio 内置 Web 服务器以及 IIS Express 7.5 进行测试。

谢谢。

4

1 回答 1

0

我认为这与请求消息的“正文样式”有关。当服务实际需要“包装”消息时,您可能会向服务发送“裸” JSON 消息(在 JSON 周围有一个额外的包装器,通常是参数名称。)

你需要注意的是WebInvokeAttribute.BodyStyle属性。它获取和设置发送到服务操作和从服务操作接收到的消息的正文样式。它控制是否包装发送到应用该属性的服务操作以及从该服务操作接收到的请求和响应。通常返回的 JSON 由可以跨域执行的 JavaScript 函数包装,因此您可能需要通过切换到“裸”主体样式来删除它。

如果将 WebInvokeAttribute 上的 BodyStyle 属性显式设置为 Bare 或 Wrapped,然后重试,会发生什么情况?这能解决你的问题吗?我觉得应该!

于 2012-04-26T20:18:57.530 回答