Ajax调用WCF Web服务将返回400错误请求
问题描述:
可能重复:
WCF Web Service returns “Bad Request” error when invoked through JavascriptAjax调用WCF Web服务将返回400错误请求
我那里有一个方法测试(一个简单的WCF Web服务服务1),它返回一个字符串。我在测试机器上部署了这个Web服务,但是当我尝试从浏览器调用Test方法时,我得到一个400错误请求错误。当我尝试通过AJAX GET请求调用该方法时会发生同样的情况。但令人惊讶的是,该方法在通过WCFTestClient调用时返回正确的结果。
下面是代码:
[ServiceContract]
public interface IService1
{
// This method can be called to get a list of page sets per report.
[OperationContract]
[WebGet]
string Test();
}
public class Service1 : IService1
{
public string Test()
{
return "test";
}
}
这是我的AJAX请求:
var serverUrl1 = 'http://' + baseUrl + ':86/Service1.svc';
function GetTestString()
{
var methodUrl = serverUrl1 + "/Test";
$.ajax({
async: false,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: methodUrl,
beforeSend: function (XMLHttpRequest) {
//ensures the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
ShowQRGSlides(data.d);
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("ERROR: GetAvailablePages() Check your browsers javascript console for more details." + " \n XmlHttpRequest: " + XmlHttpRequest + " \n textStatus: " + textStatus + " \n errorThrown: " + errorThrown);
}
});
}
这里是我的web服务的web.config文件:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="Off"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
这是只是自动生成的简单web.config。我无法弄清楚为什么这个简单的web服务方法不能通过浏览器或ajax访问。通过WCFTestClient访问时,同样的方法返回结果。
任何输入将不胜感激!谢谢。
答
您需要将服务部分添加到您的web.config文件中。除非您告诉他,否则主机不知道您要使用webHttpBinding
。下面
<services>
<service name="Service1">
<endpoint address=""
binding="webHttpBinding"
contract="IService1" />
</service>
</services>
链接提供了用于在IIS托管服务(与wsHttpBinding
)的详细说明。你只需要使用webHttpBinding
,而不是wsHttpBinding
- http://msdn.microsoft.com/en-us/library/ms733766.aspx
如果我添加的服务部分的web.config文件,然后对测试方法的调用通过浏览器,我得到500“内部服务器”与错误错误消息由于合同不匹配(发件人和收件人之间的操作不匹配),或者在发件人和收件人之间的绑定/安全不匹配,错误消息“带Action的消息”无法在接收方处理,原因可能是EndpointDispatcher中的ContractFilter不匹配。发件人和收件人检查发件人和收件人是否有相同的合同和相同的绑定(包括安全要求,例如消息,传输,无)“ – user1081934