簡體   English   中英

如何將JSON參數傳遞給RESTful WCF服務?

[英]How to pass a JSON parameter to RESTful WCF service?

我開發了Restful WCF服務,並且需要傳遞一個json字符串作為輸入。 json字符串是可變的。 這是我的服務:

[WebGet(UriTemplate = "{id}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml)]
public string GetById(string id)
{

    string sampleItem = id;


    return sampleItem;
}

這是一個json示例:

{  
   "name":"obj1",
   "x":11,
   "y":20,
   "obj":{  
      "testKey":"val"
   },
   "z":30,
   "tab":[  
      1,
      2,
      46
   ],
   "employees":[  
      {  
         "firstName":"John",
         "lastName":"Doe"
      },
      {  
         "firstName":"Anna",
         "lastName":"Smith"
      },
      {  
         "firstName":"Peter",
         "lastName":"Jones"
      }
   ]
}

http:// localhost:7626 / Service1 / myjsonstring

我收到此錯誤:Erreur HTTP 400-錯誤的請求。

PS:如果我傳遞一個簡單的字符串,它會起作用。 任何想法

首先,我建議您為此目的使用POST方法。 讀取原始字符串的最簡單方法是將其作為Stream 因此,您的服務界面可能如下所示:

[ServiceContract]
public interface IService1
{
    [WebInvoke(Method = "POST", UriTemplate = "PostJson")]
    string PostJson(Stream request);
}

並實現:

public class Service1 : IService1
{
    public string PostJson(Stream request)
    {
        using (var reader = new StreamReader(request))
        {
            return "You posted: " + reader.ReadToEnd();
        }
    }
}

另請檢查您在Web.Config中的配置是否正確:

<system.serviceModel>
  <services>
    <service name="WcfService1.Service1">
      <endpoint address="" behaviorConfiguration="restfulBehavior" 
                binding="webHttpBinding" bindingConfiguration=""
                contract="WcfService1.IService1">
      </endpoint>
    </service>
  </services>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
        <serviceMetadata httpGetEnabled="true"/>
        <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="restfulBehavior">
        <webHttp />
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

暫無
暫無

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

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