传递复杂对象到休息wcf [英] passing complex object to rest wcf

查看:240
本文介绍了传递复杂对象到休息wcf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将自定义对象传递给REST WCF操作会给我错误的请求错误。我已经尝试过这里与uri路径和查询字符串类型方法。非常感谢。任何帮助是非常感谢。

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.

服务端代码 b
$ b

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;
}

客户端代码

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();
        }
    }
}

/ strong>




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>


推荐答案

一切似乎都很好,将数据封装在包装器中,这是当你得到json数据 {mc:{name:Java}} {name:Java} 这不是包装请求。所有这些都是必需的,因为您已将 WebMessageBodyStyle 设置为已包裹

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.

下面是代码。

  [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;
            }

客户:

  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);
                }

希望有助于...

这篇关于传递复杂对象到休息wcf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆