WCF web服务从AJAX发送JSON

WCF web service sending JSON from AJAX

本文关键字:发送 JSON AJAX web 服务 WCF      更新时间:2023-09-26

嘿,我现在的代码需要一些帮助。我想通过jQuery AJAX调用将值2767994111发送到我的WCF web服务。

var parameter = { value: "2767994111" };
$('#btSubmit').click(function () {
   $.ajax({
      url: "http://localhost:65234/Service1.svc/GetData/",
      data: JSON.stringify(parameter),
      type: "GET",
      dataType: "json",
      contentType: "application/json; charset=utf-8",
      success: function (data) {
          console.log(data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert(textStatus);
      }
   });
});

IService1.vb

<ServiceContract> _
Public Interface IService1
    <OperationContract> _
    <WebGet(UriTemplate:="GetData/{value}", RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.WrappedRequest)> _
    Function getEmpData(value As String) As String
End Interface

服务1.svc

Public Class Service1
    Public Class Clocked
        Public Property [date]() As String
            Get
                Return m_date
            End Get
            Set(value As String)
                m_date = value
            End Set
        End Property
        Private m_date As String
        Public Property type() As String
            Get
                Return m_type
            End Get
            Set(value As String)
                m_type = value
            End Set
        End Property
        Private m_type As String
    End Class
    Public Class DATA
        Public Property firstName() As String
            Get
                Return m_firstName
            End Get
            Set(value As String)
                m_firstName = value
            End Set
        End Property
        Private m_firstName As String
        Public Property lastName() As String
            Get
                Return m_lastName
            End Get
            Set(value As String)
                m_lastName = value
            End Set
        End Property
        Private m_lastName As String
        Public Property emailAddress() As String
            Get
                Return m_emailAddress
            End Get
            Set(value As String)
                m_emailAddress = value
            End Set
        End Property
        Private m_emailAddress As String
        Public Property phoneNum() As String
            Get
                Return m_phoneNum
            End Get
            Set(value As String)
                m_phoneNum = value
            End Set
        End Property
        Private m_phoneNum As String
        Public Property image() As String
            Get
                Return m_image
            End Get
            Set(value As String)
                m_image = value
            End Set
        End Property
        Private m_image As String
        Public Property title() As String
            Get
                Return m_title
            End Get
            Set(value As String)
                m_title = value
            End Set
        End Property
        Private m_title As String
        Public Property clocked() As List(Of Clocked)
            Get
                Return m_clocked
            End Get
            Set(value As List(Of Clocked))
                m_clocked = value
            End Set
        End Property
        Private m_clocked As List(Of Clocked)
    End Class
    Public Class RootObject
        Public Property DATA() As DATA
            Get
                Return m_DATA
            End Get
            Set(value As DATA)
                m_DATA = value
            End Set
        End Property
        Private m_DATA As DATA
    End Class
    Public Function getEmpData(phoneNum As String) As String
        Try
            Dim connetionString As String = "Data Source=(localdb)'v11.0;Initial Catalog=stantecUsers;Integrated Security=True"
            Dim sql As String = (Convert.ToString("SELECT * " + "FROM [stantecUsers].[dbo].[users] AS stantecUsers " + "INNER JOIN [stantecUsers].[dbo].[usersData] AS stantecUserData " + "ON stantecUsers.link2Data = stantecUserData.link2Data " + "WHERE stantecUsers.phoneNum = '") & phoneNum) + "' " + "ORDER BY stantecUsers.ID ASC;"
            Dim connection As SqlConnection
            Dim command As SqlCommand
            connection = New SqlConnection(connetionString)
            ' Create a new object that matches the structure of the JSON file.
            Dim root = New RootObject() With { _
                 .DATA = New DATA() With { _
                .clocked = New List(Of Clocked)() _
                } _
            }
            Try
                connection.Open()
                command = New SqlCommand(sql, connection)
                Dim read As SqlDataReader = command.ExecuteReader()
                While read.Read()
                    root.DATA.firstName = read("firstName").ToString()
                    root.DATA.lastName = read("lastName").ToString()
                    root.DATA.phoneNum = read("phoneNum").ToString()
                    root.DATA.title = read("title").ToString()
                    root.DATA.emailAddress = read("emailAddress").ToString()
                    root.DATA.image = read("image").ToString()
                    root.DATA.clocked.Add(New Clocked() With { _
                        .[date] = read("theDate").ToString(), _
                        .type = read("theType").ToString() _
                    })
                End While
                read.Close()
                command.Dispose()
                connection.Close()
                Return JsonConvert.SerializeObject(root, Formatting.Indented)
            Catch ex As Exception
                Debug.WriteLine("Can not open connection! " + ex.Message)
                Return "Can not open connection! " + ex.Message
            End Try
        Catch e As SqlException
            Return e.Message
        End Try
    End Function
End Class

web.config

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
    <bindings>
      <webHttpBinding>
        <binding name="Binding" crossDomainScriptAccessEnabled="true">
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>
        <binding name="httpbind" crossDomainScriptAccessEnabled="true">
        </binding>
      </webHttpBinding>
    </bindings>
    <client />
    <services>
      <service name="Wcf.App.Service1"  behaviorConfiguration="ServiceBehaviour">
        <endpoint address=""
                  binding="webHttpBinding"
                  bindingConfiguration="httpbind"
                  contract="Wcf.App.IService1"
                  behaviorConfiguration="web">
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
        <behavior name="web">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

我收到的错误是:

得到http://localhost:65234/Service1.svc/GetData/?{%22value%22:%2276994111%22}500(内部服务器错误)

我真的不确定从这里到哪里去解决这个问题,所以任何帮助都会很棒!

更新@Darin Dimitrov

html页面:

var parameter = { value: "2767994111" };
$('#btSubmit').click(function () {
   $.ajax({
      url: "http://localhost:65234/Service1.svc/GetData/" + parameter.value,
      data: JSON.stringify(parameter),
      type: "GET",
      dataType: "json",
      success: function (data) {
          console.log(data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert(textStatus);
      }
   });
});

转到http://localhost:65234/Service1.svc/GetData/2767994111

"/"应用程序中的服务器错误。

找不到资源。

描述:HTTP 404。您正在查找的资源(或其依赖项)可能已被删除、名称已更改或暂时不可用。请查看以下URL并制作确保拼写正确。

请求的URL:/Service1.svc/GetData/2767994111

在发出GET请求时指定application/json内容类型是没有意义的,因为请求的正文是空的。也不要JSON.stringify,而是按照服务的期望发送url中的值:

var parameter = { value: "2767994111" };
$('#btSubmit').click(function () {
    $.ajax({
        url: "http://localhost:65234/Service1.svc/GetData/" + parameter.value,
        type: "GET",
        dataType: "json",
        success: function (data) {
            console.log(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
});

更新:

看起来您的Service1类没有实现IService1接口,这就是您获得这些404的原因。因此,请确保您正确地实现了服务接口:

Public Class Service1
    Implements IService1
    Public Function getEmpData(phoneNum As String) As String Implements IService1.getEmpData
        ... snip
    End Function
End Class