如何在ajax客户端中使用作为windows服务运行的wcf服务

时间:2011-08-22 00:11:16

标签: ajax wcf

我创建了一个WCF服务,它托管在Windows服务中。当我通过解决方案资源管理器中的右侧客户端菜单向asp.net Web表单项目添加了对该服务的Web引用时,我能够访问该服务并添加对它的引用。

现在我想通过AJAX客户端(即在ASP.NET项目中通过ScriptManager组件)访问此服务,并在计时器中调用服务以获得连续的值流。

我从未在AJAX或网络上工作太多,我没有在网上找到合适的例子。

我正在使用WSHttpBinding。


我发布了我的代码,以便您可以告诉我哪里做错了。

WCF服务库代码:

ITestService.cs代码......

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

namespace TestServiceLibrary
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
    [ServiceContract(Namespace="TestServiceLibrary")]
    public interface ITestService
    {
        [OperationContract]
        [WebGet]
        double Add(double n1, double n2);

        // TODO: Add your service operations here
    }
}

TestService.cs代码...............

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace TestServiceLibrary
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in App.config.
    public class TestService : ITestService
    {
        public double Add(double n1, double n2)
        {
            return n1 + n2;
        }
    }
}

TestServiceHost.cs(控制台应用程序的代码)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using TestServiceLibrary;

namespace TestServiceHost
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost myhost = new ServiceHost(typeof(TestService));

            myhost.Open();

            while (System.Console.ReadKey().Key != System.ConsoleKey.Enter)
            {
                //System.Threading.Thread.Sleep(100);
            }

            myhost.Close();
        }
    }
}

app.config的XML配置...在wcf服务库和wcf服务主机中都是一样的(在这种情况下是控制台应用程序..)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="TestServiceLibrary.TestService" behaviorConfiguration="TestServiceLibrary.Service1Behavior">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8731/TestServiceLibrary/TestService/" />
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint name="TestService_wsHttpBinding" address ="" binding="wsHttpBinding" contract="TestServiceLibrary.ITestService">
          <!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <!-- Metadata Endpoints -->
        <!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. --> 
        <!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="TestServiceLibrary.Service1Behavior">
          <!-- To avoid disclosing metadata information, 
          set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="True"/>
          <!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Web客户端(asp.net客户端,default.aspx)代码......

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Simple AJAX Service Client Page</title>

    <script type="text/javascript">
    // <![CDATA[

    // This function creates an asynchronous call to the service
    function makeCall(operation){
        var n1 = document.getElementById("num1").value;
        var n2 = document.getElementById("num2").value;

        // If user filled out these fields, call the service
        if(n1 && n2){

            // Instantiate a service proxy
            var proxy = new TestServiceLibrary.ITestService();

            // Call correct operation on proxy       
            switch(operation){
                case "Add":
                    proxy.Add(parseFloat(n1), parseFloat(n2), onSuccess, onFail, null);            
                break;

            }
        }
    }

    // This function is called when the result from the service call is received
    function onSuccess(mathResult){
        document.getElementById("result").value = mathResult;
    }

    // This function is called if the service call fails
    function onFail(){
        document.getElementById("result").value = "Error";
    }

    // ]]>
    </script>

</head>
<body>
    <h1>
        Simple AJAX Service Client Page</h1>
    <p>
        First Number:
        <input type="text" id="num1" /></p>
    <p>
        Second Number:
        <input type="text" id="num2" /></p>
    <input id="btnAdd" type="button" onclick="return makeCall('Add');" value="Add" />
    <p>
        Result:
        <input type="text" id="result" /></p>
    <form id="mathForm" action="" runat="server">
    <asp:ScriptManager ID="ScriptManager" runat="server">
        <Services>
            <asp:ServiceReference Path="http://localhost:8732/TestServiceLibrary/TestService/" />
        </Services>
    </asp:ScriptManager>
    </form>
</body>
</html>

在ajax中通过asp.net访问webservice时出现的错误 Microsoft JScript运行时错误:'TestServiceLibrary'未定义

请仔细阅读此代码并帮助我找到问题所在。谢谢大家的回复。

3 个答案:

答案 0 :(得分:2)

看起来问题出在我的服务托管和我正在使用的端点上。

我应该在控制台应用程序中修改我的服务托管以使用WebServiceHost而不是ServiceHost,然后只有ajax客户端可以与我的服务通信。我应该使用webHttpBinding而不是wsHttpBinding。

因此webHosting的代码如下。

using (var host = new WebServiceHost(
  typeof(TestService)))
{
    // Start listening for messages
    host.Open();

    Console.WriteLine("Press any key to stop the service.");
    Console.ReadKey();

    // Close the service
    host.Close();
}

我的控制台的xml配置是

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <services>
      <service
          name="TestServiceLibrary.TestService"
          behaviorConfiguration="">
        <endpoint address="http://localhost:8732/TestService"
           binding="webHttpBinding"
           bindingConfiguration=""
           name="TestService_WebHttp"
           contract="TestServiceLibrary.ITestService" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

现在,当我做了这个更改时,我可以通过即使用以下网址调用我的服务,即 http:// localhost:8732 / TestService / Add?n1 = 20&amp; n2 = 20 和返回的结果如下 <double xmlns="http://schemas.microsoft.com/2003/10/Serialization/">40</double>

最后我找到了解决问题的方法。我使用JSON作为通信数据的方式,接收数据的脚本如下:

<script type="text/javascript">
    $("#mybutton").click(function () {


        $.getJSON("http://localhost:8732/TestService/Add", null, function (result) {


        });

    });     
</script>

答案 1 :(得分:0)

使用像firebug这样的工具来确定请求发生了什么。 WSHttpBinding默认是安全的。检查您的安全设置。首先尝试没有安全性,以确保它不是安全问题。

答案 2 :(得分:0)

您是否曾尝试从AJAX客户端连接到该服务?如果是这样,你有任何错误吗?

如果没有看到代码,可能会有许多事情,如Chandermani所说。

我没有使用WCF进行AJAX,但是查看Preet推荐的文章,我建议您检查(如果您还没有)您的AJAX客户端根据文章提供必要的代码。

您的服务操作是否用[WebGet]修饰?

您是否正确设置了AJAX客户端的配置文件?服务的配置文件是否设置正确?