【问题标题】:WCF Web Service returns "Bad Request" error when invoked through Javascript通过 Javascript 调用 WCF Web 服务时返回“错误请求”错误
【发布时间】:2012-06-11 19:41:07
【问题描述】:

我正在尝试通过 javascript 向 WCF Web 服务方法发出 ajax GET 请求。该请求每次都返回 400“错误请求”错误。但是,如果我通过 WCF 测试客户端调用相同的 Web 服务方法,它会返回正确的结果。

此外,通过 javascript 的 ajax 调用在 GET 和 POST 请求上都返回错误请求错误。

我已将 [WebGet] 属性添加到我的 Web 服务方法,但错误仍然存​​在。

这是我的 javascript 方法和 ajax 调用:

function Getdata()
{
var methodUrl = serverUrl + "/GetData";
      $.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) {

    },
    error: function (XmlHttpRequest, textStatus, errorThrown) {
        alert("ERROR: GetData() Check your browsers javascript console for more details." + " \n XmlHttpRequest: " + XmlHttpRequest + " \n textStatus: " + textStatus + " \n errorThrown: " + errorThrown);
    }
});
}

这里,serverUrl 的格式为:“http://hostname:portnumber/webServiceProxy.svc”

知道为什么当通过 javascript 调用请求时会返回“错误请求”错误,而通过 WCF 测试客户端调用时会完美运行吗?任何输入将不胜感激!谢谢!

此外,我已经比较了从 WCF 测试客户端发出的请求和使用 Fiddler 从我的 AJAX 请求发出的请求,这是我看到的:

WCF 测试客户端请求:

POST http://hostname:portnumber/WebServiceProxy.svc HTTP/1.1
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://tempuri.org/IWebServiceProxy/GetData"
Host: hostname:portnumber
Content-Length: 144
Expect: 100-continue
Accept-Encoding: gzip, deflate

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><GetData xmlns="http://tempuri.org/"/></s:Body></s:Envelope>

我的 AJAX 请求:

GET http://hostname:portnumber/WebServiceProxy.svc/GetData HTTP/1.1
Content-Type: application/json; charset=utf-8
Accept-Language: en-us
Referer: http://hostname/OrgName/WebResources/resourceName?pagemode=iframe
Accept: application/json
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; InfoPath.3; .NET4.0E; BOIE9;ENUS)

主机:主机名:端口号 连接:保持活动状态

所以我看到的最大区别是 WCF 测试客户端发出 POST 请求并在 SOAP 信封中发送 Web 服务方法名称,而我的 ajax 请求是 GET 并将 Web 服务方法名称添加到 url。查看这些请求,关于如何更改我的 ajax 调用以使其正常工作的任何想法?谢谢!

编辑以添加我的 web.config 文件内容:

<?xml version="1.0"?>

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <customErrors mode="Off" />
</system.web>

<system.serviceModel>
    <bindings>
        <wsHttpBinding>
            <binding name="WSHttpBinding_IDDSWCFService" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                allowCookies="false">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00"
                    enabled="false" />
                <security mode="Message">
                    <transport clientCredentialType="Windows" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="Windows" negotiateServiceCredential="true"
                        algorithmSuite="Default" />
                </security>
            </binding>
        </wsHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://machinename:8080/DDSWCFService" binding="wsHttpBinding"
            bindingConfiguration="WSHttpBinding_IDDSWCFService" contract="WCFService.IDDSWCFService"
            name="WSHttpBinding_IDDSWCFService">
            <identity>

            </identity>
        </endpoint>
    </client>
    <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="true"/>
            </behavior>

        </serviceBehaviors>

        <endpointBehaviors>
            <behavior name="webHttpBehavior">
                <enableWebScript/>
                <webHttp helpEnabled="true"/>
            </behavior>
        </endpointBehaviors>

    </behaviors>
</system.serviceModel>

【问题讨论】:

  • 不看服务器配置很难判断。尝试使用 Fiddler 并比较来自 WCF 测试客户端和 Ajax 的请求。
  • 我已经编辑了我的问题并删除了 cmets 以克服格式问题。
  • 那个是服务器文件吗?我在这里只看到客户端配置。您如何托管您的服务?应该有 元素 - msdn.microsoft.com/en-us/library/ms733766.aspx 并且该服务应该在其端点中包含 binding="webHttpBinding"。
  • @dharnitski 现在我只是想测试 Web 服务代理,所以我在本地机器上将实际的 Web 服务作为控制台应用程序运行,并通过托管在另一台机器。所以我发布的网络配置是针对代理的。
  • 我需要服务器配置文件并了解您如何托管它。客户端代码好像没问题,但是服务不支持AJAX。

标签: javascript wcf


【解决方案1】:

我看到WCF测试客户端请求的最大区别 我的 ajax 请求是我发出 GET 请求并传入名称 url 中的 web 服务方法,而 WCF 测试客户端进行 发布请求并在 SOAP 中发送 Web 服务方法名称 信封。

您的服务似乎配置了 SOAP 绑定,无法使用 AJAX Get 请求。

如果你想从 JS 消费你的服务,你需要使用WebHttpBinding

  1. 添加[WebGet]属性得到你的操作
  2. 更改端点中的绑定 - binding="webHttpBinding"
  3. 为端点配置行为

互联网上有很多示例。比如这个http://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/

<endpointBehaviors>
  <behavior name="webBehavior">
    <webHttp />
  </behavior>
</endpointBehaviors>

您需要将服务部分添加到您的 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 内容添加到问题中。任何意见将不胜感激!
【解决方案2】:

我希望您的服务在您使用它的另一个域中运行。在这些情况下,您必须使用 JSONP 调用。

dataType修改为jsonp

$.ajax({
  //..
  dataType: "jsonp",
  //..
});

【讨论】:

    【解决方案3】:

    感谢所有回复。令人惊讶的是,我设法修复了错误,但解决方案完全不是我所期望的。我必须在 Service1.svc 文件的标记中添加一个附加属性:

    Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory

    我不确定为什么在构建项目时它没有自动添加到文件中,但就是这样做的。我现在可以毫无问题地通过浏览器以及我的 AJAX 请求调用 Test 方法。

    再次感谢大家的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多