Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

passing complex object to rest wcf

Passing custom object to REST WCF operation is giving me "bad request error". I have tried here with both uri path and query string type methods.Any help is greatly appreciated.

service side code

[ServiceContract]    
public interface IRestService
{       

   [OperationContract]        
   [WebInvoke(UriTemplate  = "getbook?tc={tc}",Method="POST",BodyStyle=WebMessageBodyStyle.Wrapped,RequestFormat=WebMessageFormat.Json)]
   string GetBook(myclass mc);
}

[DataContract]
[KnownType(typeof(myclass))]
public class myclass
{
    [DataMember]
    public string name { get; set; }        
}

public string GetBookById(myclass mc)
{            
    return mc.name;
}

client side code:

public static void GetString()
{
    myclass mc = new myclass();            
    mc.name = "demo";           

    string jsn = new JavaScriptSerializer().Serialize(mc);

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(string.Format(@"http://localhost:55218/RestService.svc/getbook?mc={0}",jsn));

    string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("bda11d91-7ere-4da1-2e5d-24adfe39d174"));
    req.Headers.Add("Authorization", "Basic " + svcCredentials);
    req.MaximumResponseHeadersLength = 2147483647;
    req.Method = "POST";           
    req.ContentType = "application/json";   
    // exception is thrown here         
    using (WebResponse svcResponse = (HttpWebResponse)req.GetResponse())
    {
        using (StreamReader sr = new StreamReader(svcResponse.GetResponseStream()))
        {
          JavaScriptSerializer js = new JavaScriptSerializer();
          string jsonTxt = sr.ReadToEnd();
        }
    }
}

service config

<basicHttpBinding>
  <binding name="BasicHttpBinding_IService" closeTimeout="01:01:00"
    openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00"
    allowCookies="false" bypassProxyOnLocal="false"  hostNameComparisonMode="StrongWildcard"
    maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
    messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed"
    useDefaultWebProxy="true">
    <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
      maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
    <security mode="None">
      <transport clientCredentialType="None" proxyCredentialType="None"
        realm="" />
      <message clientCredentialType="UserName" algorithmSuite="Default"/>
    </security>
  </binding>
</basicHttpBinding>

<webHttpBinding>
  <binding name="" closeTimeout="01:01:00" openTimeout="01:01:00" 
    receiveTimeout="01:10:00" sendTimeout="01:01:00" allowCookies="false"
    bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
    maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
    transferMode="Streamed" useDefaultWebProxy="true">
    <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
      maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
    <security mode="None" />
   </binding>
 </webHttpBinding>
 </bindings>

<services>
  <service name="WcfRestSample.RestService" behaviorConfiguration="ServiceBehavior">
    <endpoint address="" behaviorConfiguration="restfulBehavior"
      binding="webHttpBinding" bindingConfiguration="" contract="WcfRestSample.IRestService" />        
    <!--<host>
      <baseAddresses>
        <add baseAddress="http://localhost/restservice" />
      </baseAddresses>
    </host>-->
  </service>
</services>
<!-- behaviors settings -->
<behaviors>     

  <!-- end point behavior-->
  <endpointBehaviors>
    <behavior name="restfulBehavior">          
      <webHttp/>               
    </behavior>
  </endpointBehaviors>

  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceAuthorization serviceAuthorizationManagerType="WcfRestSample.APIKeyAuthorization, WcfRestSample" />
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>      
 </behaviors>
 <standardEndpoints>
  <webHttpEndpoint>
    <standardEndpoint
      automaticFormatSelectionEnabled="true"
      helpEnabled="true" />
 </webHttpEndpoint>
 </standardEndpoints>
 <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
 </system.serviceModel>
 <system.webServer>
 <modules runAllManagedModulesForAllRequests="true" />
 </system.webServer>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Everything seems to be fine, except that you have to wrap the data in a wrapper, and that is when you get the json data as {"mc":{"name":"Java"}} else you will get only {"name":"Java"} which is not a wrapped request. All these is required because you have set the WebMessageBodyStyle as Wrapped.

Below is the code.

  [OperationContract]
            [WebInvoke( Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json)]
            string GetBook(myclass mc);

     [DataContract]    
        public class myclass
        {
            [DataMember]
            public string name { get; set; }
        }

public string GetBook(myclass mc)
            {
                return mc.name;
            }

Client:

  public class wrapper
    {
        public myclass mc;
    }
    public class myclass
    {
        public String name;
    }

    myclass mc = new myclass();
                mc.name = "Java";
                wrapper senddata = new wrapper();
                senddata.mc = mc;
                JavaScriptSerializer js = new JavaScriptSerializer();
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] data = encoder.GetBytes(js.Serialize(senddata));
                HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create(String.Format(@"http://localhost:1991/Service1.svc/GetBook?"));
                req2.Method = "POST";
                req2.ContentType = @"application/json; charset=utf-8";
                req2.MaximumResponseHeadersLength = 2147483647;
                req2.ContentLength = data.Length;
                req2.GetRequestStream().Write(data, 0, data.Length);
                HttpWebResponse response = (HttpWebResponse)req2.GetResponse();
                string jsonResponse = string.Empty;
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    jsonResponse = sr.ReadToEnd();
                    Response.Write(jsonResponse);
                }

Hope that helps...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...