通过Javascript调用时,WCF Web服务返回“错误请求”错误

时间:2012-06-11 19:41:07

标签: javascript wcf

我正在尝试通过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)

主持人:hostname:portnumber     连接:Keep-Alive

因此,我看到的最大区别是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>

3 个答案:

答案 0 :(得分:1)

  

我看到了WCF测试客户端请求之间的最大区别   我的ajax请求是我发出GET请求并传入名称   在WCF测试客户端创建时,URL中的Web服务方法   发布请求并在SOAP中发送Web服务方法名称   信封。

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

如果您想从JS使用服务,则需要使用WebHttpBinding

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

    互联网上有很多样本。例如,这一个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

答案 1 :(得分:0)

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

dataType修改为jsonp

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

答案 2 :(得分:0)

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

厂=“System.ServiceModel.Activation.WebScriptServiceHostFactory

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

再次感谢大家的帮助。