【发布时间】:2011-03-19 14:26:47
【问题描述】:
我有一个可以通过 jQuery 调用的 WCF 服务,但我无法通过 HttpWebRequest 调用。我之前已经能够使用完全相同的 HttpWebRequest 设置来调用 ASMX 服务,但这是我第一次尝试调用 WCF 服务。我提供了 jQuery 和 C# HttpWebRequest 代码,因此您希望能注意到我做的一些明显错误的事情。
这是我损坏的 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"};
}
【问题讨论】:
标签: c# wcf httpwebrequest