【发布时间】:2012-06-16 02:34:39
【问题描述】:
可能重复:
WCF Web Service returns “Bad Request” error when invoked through Javascript
我有一个简单的 WCF Web 服务 Service1,它只有一个返回字符串的方法 Test()。我已经在测试机器上部署了这个 Web 服务,但是当我尝试从浏览器调用 Test 方法时,我只是收到 400 Bad Request 错误。当我尝试通过 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.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。我无法弄清楚为什么无法通过浏览器或 ajax 访问这种简单的 Web 服务方法。通过 WCFTestClient 访问时,同样的方法返回结果。
任何输入将不胜感激!谢谢。
【问题讨论】:
标签: ajax wcf web-services