从jquery Ajax调用WCF服务

Pri*_*era 5 c# ajax wcf jquery json

我正在尝试创建一个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);
}
Run Code Online (Sandbox Code Playgroud)

履行

public User AddUser(User user)
{
    return userRepository.Add(user);
}
Run Code Online (Sandbox Code Playgroud)

配置

<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>
Run Code Online (Sandbox Code Playgroud)

从客户端,我使用以下代码来调用该服务.

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.');
    }
}
Run Code Online (Sandbox Code Playgroud)

当我打电话给服务时,我收到了错误请求.

MSU*_*SUH 1

问题可能与“localhost:36908”相关,您需要确保您的服务已启动并托管在同一端口上,您可以转到 WCF 项目属性并选择“使用 Visual Studio 开发服务器”,选中“特定端口”选项并在其中写入 36908,然后启动开发服务器或调试启动解决方案,再次尝试点击 url。