调用WCF服务时出现ajax错误

本文关键字:ajax 错误 WCF 服务 调用 | 更新日期: 2023-09-27 18:11:23

我在Test.cs中有这个WCF方法

[OperationContract]
    [WebInvoke(Method = "POST",
               BodyStyle = WebMessageBodyStyle.Wrapped,
               ResponseFormat = WebMessageFormat.Json)]
    public string Test()
    {
        return "ok";
    }

Test.svc:

 <%@ ServiceHost Language="C#" Debug="true"   Service="Test" CodeBehind="Test.cs" %>

这在我的本地机器上运行正常,我在IIS7中托管客户端和WCF。然而,当我将它部署到我们的测试服务器时,我得到了这个:当进行WCF调用时,我了解服务器之间的跨站点脚本限制,但是,我与客户端和WCF处于同一域。

客户端:http://mydev.test.com/Test.aspx

服务器:http://devwcf.test.com/Test.svc

Ajaxerror 0未定义的

Ajax调用:

$(document).ready(function () {
        $.ajax({
            url: "http://localhost/Test.svc/Test",
            type: "POST",
            contentType: "application/json",
            datatype: "json",
            data: "{}",
            cache: false,
            success: function (result) { alert(result.TestResult) },
            //error: ServiceFailed
            error: function (request, status, error) {
                alert(status);
            }
        });
    });

网络。配置:

<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="true" targetFramework="4.0">
  <assemblies>
  </assemblies>
</compilation>
<authentication mode="Windows"/>
</system.web>
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<behaviors>
  <endpointBehaviors>
    <behavior name="EndpBehavior">
      <webHttp />
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="ServiceBehavior" name="Test">
    <endpoint address="" binding="webHttpBinding" contract="Test" behaviorConfiguration="EndpBehavior"/>
  </service>
</services>
</system.serviceModel>
</configuration>

调用WCF服务时出现ajax错误

您不在同一域名上,因为客户端和服务的子域名不同,浏览器仍然会将其视为跨域。您需要为您的服务启用CORS,需要在您的web中进行一些更改。config OR global.asax.cs

在你的网页。设置

<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>

在服务模型下把它放在serviceHostingEnvironment

下面
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint name="" crossDomainScriptAccessEnabled="true" />
</webScriptEndpoint>
</standardEndpoints>

如果您选择Global.asax.cs,则连接beginrequest事件并设置标头,在这种情况下不需要上述配置

  protected void Application_BeginRequest(object sender, EventArgs e)
    {
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , ”*”);
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS" )
    {
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" );
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers" , "Content-Type, Accept" );
    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age" "1728000" );
    HttpContext.Current.Response.End();
    }
    } 

此外,您也可以在wcf方法中设置这些头,建议:

if (WebOperationContext.Current.IncomingRequest.Method == "OPTIONS")
               {
                   WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "http://Server:Port"); // * doesn't work
           WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "GET");
           WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST");
           WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");
                   return null;
               }

要了解更多关于CORS的信息,

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing其他解决方法是使用JSONP,使用JSONP自定义行为:http://lucbei.wordpress.com/2010/09/06/cross-domain-wcf-rest-with-js-call-3-5-solution