对WCF Web服务的Ajax调用返回400 Bad Request

时间:2012-06-13 19:57:00

标签: ajax wcf web-services

  

可能重复:
  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。我无法弄清楚为什么这个简单的Web服务方法无法通过浏览器或ajax访问。当通过WCFTestClient访问时,相同的方法返回结果。

任何输入都将不胜感激!感谢。

1 个答案:

答案 0 :(得分:1)

您需要在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