我有一個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"};
}