0

可能重复:
通过 Javascript 调用 WCF Web 服务时返回“错误请求”错误

我有一个简单的 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 服务的 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 访问时,相同的方法返回结果。

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

4

1 回答 1

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

于 2012-06-13T20:24:13.400 回答