簡體   English   中英

從jquery Ajax調用WCF服務

[英]Calling WCF service from jquery Ajax

我正在嘗試創建一個WCF服務並使用jquery AJAX調用其方法。 到目前為止,我還沒弄清楚如何做到這一點。 我已經閱讀了SO中給出的一些解決方案,但仍然無法修復它。 任何幫助,將不勝感激。 我有以下代碼。

在WCF服務中。

服務合約

[ServiceContract]
public interface IDatingService
{
[WebInvoke(Method = "POST",
RequestFormat= WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "/AddUser")]
    [OperationContract]
    User AddUser(User user);
}

履行

public User AddUser(User user)
{
    return userRepository.Add(user);
}

配置

<system.serviceModel>
 <behaviors>
  <serviceBehaviors>
    <behavior name="DatingServiceBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="DatingServiceBehavior">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="DatingServiceBehavior"
           name="DatingService.Service.DatingService">
    <endpoint address="" binding="webHttpBinding"
       contract="DatingService.Service.IDatingService"
       behaviorConfiguration="DatingServiceBehavior"/>
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
  </service>
 </services>
</system.serviceModel>

從客戶端,我使用以下代碼來調用該服務。

saveInfo: function () {
    console.log('saveInfo');
    if ($('#terms-check').is(":checked")) {
        if (app.validateEmail()) {
            var input =
                {
                    "user":
                    {
                        "LoginId": user.LoginId.text(),
                        "Password": user.Password.text(),
                        "Email": user.Email.val()
                    }
                };
            $.ajax({
                type: "POST",
                url: "http://localhost:36908/DatingService.svc/AddUser",
                data: JSON.stringify(input),
                contentType: 'application/json; charset=utf-8',
                dataType: "json",
                success: app.onSaveSuccess,
                error: app.onSaveError
            });
        }
        else {
            $('.error-label').text('Invalid email address.');
        }
    }
    else {
        $('.error-label').text('Please check the terms and conditions.');
    }
}

當我打電話給服務時,我收到了錯誤請求。

問題可能與“localhost:36908”有關,您需要確保您的服務已啟動並托管在同一端口上,您可以轉到WCF項目屬性並選擇“使用Visual Studio開發人員服務器”,選中“特定端口”選項並在其中寫入36908,然后啟動開發服務器或調試啟動解決方案,嘗試再次點擊該URL。

你應該構造這樣的對象。你得到400 Bad請求,因為wcf需要ajax沒有發送的格式的數據。

var obj = {};
obj.LoginId = user.LoginId.text();
obj.Password = user.Password.text();
obj.Email =  user.Email.val();

var jsonObj=JSON.stringify(obj);
var dataToSend = '{"user":'+jsonObj+'}';

然后在ajax查詢中更改數據部分

       $.ajax({
                type: "POST",
                url: "http://localhost:36908/DatingService.svc/AddUser",
                data: JSON.stringify({user:obj}),
    or
                data: dataToSend,
                contentType: 'application/json; charset=utf-8',
                dataType: "json",
                success: app.onSaveSuccess,
                error: app.onSaveError
            });

暫無
暫無

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

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