调用WCF服务时出现Ajaxerror

时间:2014-07-03 15:23:56

标签: c# jquery asp.net wcf

我在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);
            }
        });
    });

Web.Config中:

<?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>

1 个答案:

答案 0 :(得分:0)

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

在你的web.config中放置以下设置

<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,wcf JSONP自定义行为: http://lucbei.wordpress.com/2010/09/06/cross-domain-wcf-rest-with-js-call-3-5-solution