簡體   English   中英

WCF服務中的WebScriptEnablingBehavior不適用於POST方法

[英]WebScriptEnablingBehavior in WCF service doesn't work with POST method

我想在WCF REST服務中利用WebScriptEnablingBehavior的功能來生成javascript客戶端代理(以及隨之而來的強類型對象)。
它可以與GETclient.DownloadData()方法(作為查詢字符串傳遞的參數)配合使用,但是我正努力使其與POSTclient.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());

請注意,如果我不使用WebScriptEnablingBehavior而是使用webHttpURITemplate ,則可以正常工作。
已通過Visual Studio內置Web服務器以及IIS Express 7.5進行了測試。

謝謝。

我認為這與請求消息的“主體樣式”有關。 當服務實際期望“包裝”消息時,您可能正在向該服務發送“裸” JSON消息(帶有附加的JSON包裝,通常是參數名稱)。

您需要注意的是WebInvokeAttribute.BodyStyle屬性。 它獲取並設置發送到服務操作和從服務操作發送的消息的正文樣式。 它控制是否包裝發送給屬性應用到的服務操作的請求和響應。 通常,返回的JSON被可以跨域執行的JavaScript函數包裝,因此您可能需要通過切換為“裸露”樣式來刪除它。

如果將WebInvokeAttribute的BodyStyle屬性顯式設置為Bare或Wrapped,然后重試,會發生什么情況? 這樣可以為您解決問題嗎? 我認為應該!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM