将自定义对象传递给REST WCF操作会给我“错误的请求错误”。我在这里尝试了uri路径和查询字符串类型方法。非常感谢任何帮助。
服务端代码
[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();
}
}
}
服务配置
<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 :(得分:0)
一切似乎都很好,除了你必须将数据包装在一个包装器中,那就是当你将json数据作为{"mc":{"name":"Java"}}
时,你将只得到{"name":"Java"}
这不是一个包裹请求。所有这些都是必需的,因为您已将 WebMessageBodyStyle 设置为 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);
}
希望有帮助...