2013-05-01 134 views
0

我想向我的Web控件类项目添加一个WCF服务,并允许我的jQuery客户端使用该服务。理想情况下,我想在同一个项目中托管WCF服务,并允许自定义Web控件(在同一项目中)jQuery方法使用该服务。我不确定我做错了什么,但我无法在jquery调用和服务之间建立连接。尽管没有错误,但我的服务中断点始终没有达到。下面是我做的:从JQuery消费WCF服务

  1. 右键单击项目,然后选择添加
  2. 选择Web服务
  3. 这将创建三个文件:Service1.vb,App.config,并将IService1.vb
  4. 我编辑这些文件看起来像这样:

服务1

Public Class Service1 
    Implements IService1 

    Public Function getUsers(ByVal prefixText As String) As List(Of String) Implements IService1.getUsers 
     Dim myList As New List(Of String) 
     With myList 
      .Add("Some String") 
      .Add("Another String") 
     End With 

     Return myList 
    End Function 
End Class 

IService1

Imports System.ServiceModel 

<ServiceContract()> 
Public Interface IService1 

    <OperationContract()> _ 
    Function getUsers(ByVal prefixText As String) As List(Of String) 

End Interface 

然后我尝试用下面的jQuery来调用它:

$.ajax({ 
     type: "POST", 
     url: 'Service1.vb/getUsers',   
     data: '{"prefixText":"' + getText + '"}', 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (msg) { 
      alert("success") 

     }, 
     error: function (e) { 
      alert("Failed") 
     } 
    }); 

正如我所说的,是从来没有达到我的getUsers函数断点和jQuery的成功/失败警报永远不会提出。如果有人能告诉我如何访问服务和/或如何警告我的jQuery中的错误,我会很感激。我遗漏了app.config的东西,但可以添加它,如果它会有所帮助。

谢谢

回答

0

这是在你的代码中的一个可怕的误解。默认情况下,WCF使用Soap和Javascript/Jquery不提供调用SOAP服务的简单方法。

您应该使用WCF的Web HTTP编程模型公开给非SOAP端点WCF服务操作,就像一个REST式服务(可从JS调用)

IY您正在使用WCF 4,这是相当简单。

服务合同

<ServiceContract()> 
Public Interface IService1 

    <OperationContract()> 
    <WebInvoke(BodyStyle:=WebMessageBodyStyle.Bare, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)> 
    Function getUsers() As List(Of String) 

End Interface 

服务实现

Public Class Service1 
    Implements IService1 

    Public Function getUsers(ByVal prefixText As String) As List(Of String) Implements IService1.getUsers 
     Dim myList As New List(Of String) 
     With myList 
      .Add("Some String") 
      .Add("Another String") 
     End With 

     Return myList 
    End Function 

End Class 

Service1.svc

<%@ ServiceHost Language="VB" 
Service="MvcApplication2.Service1" 
CodeBehind="Service1.svc.vb" 
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %> 

我禾不解释你在这里的一切,并继续阅读here或与此example

另请注意,由于ASP.NET Web Api,WCF REST今天不太受欢迎。我不相信WCF REST已被弃用,但为了暴露Web上的某些内容,Web Api听起来像是一个更好的解决方案。

+0

感谢您的回复。当我按照你的建议创建我的服务时,没有创建svc文件。这是我应该创建一个文本文件并重命名吗? – jason 2013-05-06 13:24:29

+0

是的,但在WCF新的项目模板中,这个文件是自动的 – Cybermaxs 2013-05-06 14:02:34

+0

好吧,我想我得到这个。两件事情。首先,我看到Service1.SVC中有“Service =”MvcApplication2.Service1“。我没有使用MVC(这是在服务器控件中)。它应该是服务的全名,IE:com。 jason.Service1?第二,我如何在jqeury中访问它?特别是在jQuery? – jason 2013-05-06 14:22:14