2013-12-18 2 views
2

사용자 지정 개체를 REST WCF 작업에 전달하면 "잘못된 요청 오류"가 발생합니다. 나는 uri path와 query string type methods.Any help로 큰 도움을주었습니다. 복잡한 개체를 wcf로 전달

서비스 측 코드

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

서비스 설정

,451,515,
<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> 
+0

. bodystyle 속성 값을 Bare로 변경하고 시도해 볼 수 있습니까? 또한 Fiddler를 사용하여 Raw 요청을 검사하고 여기에 요청을 게시하여 도움을 받으십시오. – Rajesh

+0

서비스 구성 파일도 게시하십시오. – Tim

+0

나는 또한 서비스 설정을 포함하는 나의 질문을 업데이트했다. 이 코드에서는 basichttpbinding 구성을 설정 한 다른 서비스 (예 : service.svc)를 호출하려고합니다. 이 두 번째 서비스를 호출하여 잘못된 요청 오류가 발생합니다. 내가 어디로 잘못 가고 있는지 모르겠다. –

답변

0

모든 것은 당신이 래퍼의 데이터를 마무리해야하는 것을 제외하고, 잘 될 것 같다, 당신은 다른 사람이 포장 요청하지 않은 경우에만 {"name":"Java"}을 얻을 것이다 {"mc":{"name":"Java"}}로 JSON 데이터를 얻을 때이다. 당신이으로는을 싸서 WebMessageBodyStyle를 설정했기 때문에이 모든이 필요합니다.

다음은 코드입니다.

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

희망 ... 포장하지만 요청이 적절하게 포장되지 않는다는 것을 가정하고 같이가 bodystyle 속성을 사용하는

+0

안녕하세요 @ Saranya, 답장을 보내 주셔서 감사합니다. 나는 당신의 코드를 점검 할 것이다. –