我有一个WCF服务,我可以通过jQuery调用,但我无法通过HttpWebRequest调用。我已经能够使用完全相同的HttpWebRequest设置来调用ASMX服务,但这是我第一次尝试调用WCF服务。我已经提供了jQuery和C#HttpWebRequest代码,所以你可以很有希望地注意到我所做的显然是错误的。获取HTTP错误400通过HttpWebRequest调用WCF服务
这是我破碎的C#代码,最后一行抛出错误400
string url = "http://www.site.com/Service/Webapi.svc/GetParts";
string parameters = "{part: 'ABCDE'}";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentLength = 0;
req.ContentType = "application/json; charset=utf-8";
if (!string.IsNullOrEmpty(parameters))
{
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
req.ContentLength = byteArray.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
这是我工作的jQuery代码
$.ajax({
url: '/Service/Webapi.svc/GetParts',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
data: JSON.stringify({ part: request.term }),
success: function (data) {
// Success
}
});
这里是我的亲戚web.config设置
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="REST">
<enableWebScript/>
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<services>
<service name="Webapi">
<endpoint address="" behaviorConfiguration="REST" binding="webHttpBinding" contract="IWebapi"/>
</service>
</services>
</system.serviceModel>
这里是我的服务界面,我试着改变“方法”到“POST”,但这并没有使广告。差分。
[ServiceContract]
public interface IWebapi
{
[OperationContract]
[WebInvoke(
Method = "*",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)
]
string[] GetParts(string part);
}
这里是我的服务实现
public string[] GetParts(string part)
{
return new string[] {"ABC", "BCD", "CDE"};
}