在MVC 4应用程序中使用jQuery $ .ajax来使用RESTful WCF服务

时间:2014-01-12 15:02:31

标签: jquery ajax asp.net-mvc wcf

对于MVC 4应用程序,我正在尝试使用jQuery $ .ajax函数来使用RESTful WCF服务,我正面临着它的问题。

下面是我的jQuery代码,

$(document).ready(function () {
$.ajax({
    type: "GET",
    url: "http://localhost:55205/Services/UserService.svc/GetUserProjects",
    data: '{"gpn": "' + 1 + '"}',
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    success: function (data, textStatus, jqXHR) {
        alert(textStatus);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(textStatus);
    },
    complete: function (jqXHR, textStatus) {
    }
});

});

以下是我的WCF配置

<system.serviceModel>
<services>
  <service name="BugTracker.WcfService.Services.UserService" behaviorConfiguration="BugTracker.WcfService.Services.UserServiceServiceBehavior">
    <endpoint address="" behaviorConfiguration="BugTracker.WcfService.Services.UserServiceAspNetAjaxBehavior"
      binding="webHttpBinding" contract="BugTracker.WcfService.Services.IUserService" />
  </service>
</services>
<behaviors>
  <endpointBehaviors>
    <behavior name="BugTracker.WcfService.Services.UserServiceAspNetAjaxBehavior">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="BugTracker.WcfService.Services.UserServiceServiceBehavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<bindings>
  <webHttpBinding>
    <binding name="" crossDomainScriptAccessEnabled="true"></binding>
  </webHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
  multipleSiteBindingsEnabled="true" />
<standardEndpoints>
  <webHttpEndpoint>
    <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"></standardEndpoint>
  </webHttpEndpoint>
</standardEndpoints>

下面是我的WCF代码,

 [ServiceContract]
public interface IUserService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetUserProjects/{gpn}")]
    IList<Project> GetUserProjects(String gpn);
}

我面临的问题是,当我尝试调试代码时,没有点击WCF服务实现。该服务不会随时点击。

任何人都可以建议我写的代码是正确的代码还是我遗漏了什么?

请建议。提前致谢

1 个答案:

答案 0 :(得分:0)

尝试将此更改'GET'改为'POST'

$(document).ready(function () {
$.ajax({
    type: "POST",
    url: "http://localhost:55205/Services/UserService.svc/GetUserProjects",
    data: '{"gpn": "' + 1 + '"}',
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    success: function (data, textStatus, jqXHR) {
        alert(textStatus);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(textStatus);
    },
    complete: function (jqXHR, textStatus) {
    }
});
});