簡體   English   中英

如何配置通過跨域AJAX調用的WCF服務

[英]How Do I Configure a WCF Service to Be Called Via Cross-Domain AJAX

我在配置WCF服務以允許通過跨域AJAX進行消費時遇到了一些困難。

我已經成功地在客戶端上成功使用了該服務,但是每次嘗試使用AJAX來實現該服務時(通過jQuery中的$ .ajax對象),都會出現400錯誤。

這是我的web.config

<?xml version="1.0"?>
<configuration>
    <system.web>
        <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
    </system.web>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="basicHttpBinding" />
            </basicHttpBinding>
            <mexHttpBinding>
                <binding name="mexHttpBinding" />
            </mexHttpBinding>
            <webHttpBinding>
                <binding name="webHttpBinding" crossDomainScriptAccessEnabled="true">
                    <security mode="None" />
                </binding>
            </webHttpBinding>
        </bindings>
        <services>
            <service name="Services.WebAnalyticsService">
                <clear />
                <endpoint binding="basicHttpBinding" bindingConfiguration="basicHttpBinding"
                 name="WebAnalyticsDotNetClientEndpoint" contract="Contracts.IWebAnalyticsService"
                 listenUriMode="Explicit" />
                <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="mexHttpBinding"
                 name="WebAnalyticsMetaDataEndpoint" contract="Contracts.IWebAnalyticsService"
                 listenUriMode="Explicit" />
                <endpoint address="script" behaviorConfiguration="aspNetAjaxBehavior"
                 binding="webHttpBinding" bindingConfiguration="webHttpBinding"
                 name="WebAnalyticsAjaxEndpoint" contract="Contracts.IWebAnalyticsService" />
                <!--<endpoint address="web" behaviorConfiguration="RESTBehavior"
                 binding="webHttpBinding" bindingConfiguration="webHttpBinding"
                 name="WebAnalyticsAjaxEndpoint" contract="Contracts.IWebAnalyticsServiceWeb"  />-->
            </service>
        </services>
        <behaviors>
            <endpointBehaviors>
                <behavior name="aspNetAjaxBehavior">
                    <enableWebScript />
                </behavior>
                <!--<behavior name="RESTBehavior">
                    <webHttp helpEnabled="true"/>
                </behavior>-->
            </endpointBehaviors>
            <serviceBehaviors>
                <behavior>
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>
        <system.diagnostics>
            <sources>
                <source name="System.ServiceModel"
                    switchValue="Information, ActivityTracing"
                    propagateActivity="true">
                    <listeners>
                        <add name="xml"
                 type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="c:\log\Traces.svclog" />
                    </listeners>
                </source>
            </sources>
        </system.diagnostics>
</configuration>

這是我的運營合同。

Namespace Contracts

        <ServiceContract()>
 Public Interface IWebAnalyticsService

    <OperationContract(), WebGet(RequestFormat:=WebMessageFormat.Json)>
    Sub SendWaEvent(ByVal eventID As Integer, ByVal eventValue As String, _
      ByVal cookieVisitID As String, ByVal cookieVisitorSession As String, _
      ByVal HTTPXForwardedServer As String, ByVal HTTPXRewriteURL As String, _
      ByVal ScriptName As String, ByVal ServerName As String)

    End Interface

End Namespace

我的Ajax調用非常簡單,但是這里是:

$.ajax({
  type: 'POST',
  crossDomain: true,
  url: 'http://localhost:37490/services/webanalyticservice.svc/SendWaEvent',
  data: Data, //Data is a JSON wrapper I've previously constructed.
  contentType: 'application/javascript;charset=UTF-8'
  success: function(result) {DoSomething(result);},
  error: HandleError
});

[ 更新如下 ]

總是我們忽略的東西,不是嗎? 無論如何,在對上面的“直接” AJAX調用非常不屑一顧之后,它最終成為了問題。 為了使它正常工作,我不得不將我的AJAX調用更改為:

        function SendAJAX() {
            $.ajax({ type: "GET",
                url: URL,
                data: Data,
                dataType: 'jsonp',
                jsonpCallback: 'MyCallBack',
                timeout: 10000,
                crossDomain: true,
                contentType: 'application/json; charset=UTF-8',
                success: function (data, textStatus, jqXHR) { WriteSuccess(data, textStatus, jqXHR) },
                error: function (jqXHR, textStatus, errorThrown) { WriteError(jqXHR, textStatus, errorThrown) },
                complete: function (jqXHR, textStatus) { }
            });
        }

另外,請注意,如果您要在本地進行測試,則需要將以下內容添加到您的網絡配置中,否則將收到500錯誤消息,提示已驗證的服務中不允許使用跨域JavaScript。

<system.web>
    <authentication mode="None" />
</system.web>

您可以使用xdt:transform在web.release.config中刪除此屬性。

向@Rajesh大聲喊叫! 干得好,伙計!

您的JQuery函數需要如下所示:

function TestingWCFRestWithJsonp() {
                $.ajax({
                    url: "http://localhost:37490/services/webanalyticservice.svc/script/SendWaEvent",
                    dataType: "jsonp",
                    type: "GET",
                    timeout: 10000,
                    jsonpCallback: "MyCallback",
                    success: function (data, textStatus, jqXHR) {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {    
                    },
                    complete: function (jqXHR, textStatus) {
                    }
                });
            }
            function MyCallback(data) {
                alert(data);
            }

由於您的終結點元素設置了地址值,因此需要將其附加到.svc的末尾,然后提供方法名稱,如下面的示例中所示。

綁定元素上的crossDomainScriptAccessEnabled屬性標識您的請求是否指定了回調方法,並將響應寫回到流中。

注意:從您的瀏覽器測試URL,以查看您是否以WebGet方法獲得成功的響應

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM