如何使用WCF服务运行为Windows服务在AJAX客户端如何使用、客户端、Windows、WCF

2023-09-11 00:35:26 作者:拽拽拽〃起来

我创建了一个WCF服务,并托管在Windows服务。当我在Solution Explorer中添加的Web引用该服务以一个asp.net web窗体项目,通过正确的客户端菜单中我能够访问该服务,并添加引用。

I have created a WCF service and it is hosted in windows service. When I have added a web reference to that service to an asp.net web forms project through right client menu in the solution explorer I am able to access the service and add reference to it.

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

Now I want to access this service through AJAX client (i.e in ASP.NET project through ScriptManager component)and call the service in a timer to get continuous stream of values.

我从来没有对AJAX或网站那么多,我没有找到这样的一个合适的例子净。

I have never worked on AJAX or web that much, I did not find an suitable example on net on this.

我使用的WSHttpBinding。

I'm using WSHttpBinding.

我张贴我的code,这样就可以知道你们在哪里,我做错了。

I'm posting my code so that you can tell where I'm doing wrong.

WCF服务库code:

WCF Service Library Code:

ITestService.cs code ....

ITestService.cs code....

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 code ...............

TestService.cs code...............

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($ C $的控制台应用程序C)

TestServiceHost.cs (code of console application)

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 Configuration of app.config... same in both wcf service library and wcf service host(console application in this case..)

<?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的)code ...

Web Client (asp.net client, default.aspx) code...

<!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>

林通过asp.net阿贾克斯在访问webservice时正的错误是微软JScript运行时错误:TestServiceLibrary未定义

请通过这个code,帮我找到这个问题。谢谢大家对你的反应。

Please go through this code and help me in finding the problem. Thank you all for your responses.

推荐答案

看起来,问题是我的服务托管和我使用的端点。

Looks like the problem is with my service hosting and the endpoint i'm using.

我要修改我的服务托管在控制台应用程序中使用WebServiceHost而不是ServiceHost的,则只有AJAX客户端可以跟我的服务。相反的wsHttpBinding,我应该使用的WebHttpBinding。

I should modified my service hosting in the console application to use WebServiceHost instead of ServiceHost, then only the ajax clients can talk to my service. Instead of wsHttpBinding, I should use webHttpBinding.

所以,$ C $下的虚拟主机如下。

So the code for webHosting is as follows.

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配置

The xml configuration of my console is

<?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>

现在,当我这样做改变了,我能够通过IE使用以下URL来叫我的服务即的http://本地主机:8732 / TestService的/添加N1 = 20安培; N2 = 20 和结果返回的是如下的 &LT;双层的xmlns =htt​​p://schemas.microsoft.com/2003/10/Serialization/&GT; 40℃/双&GT;

Now when I did this changes I'm able to call my service through ie using the following url in ie http://localhost:8732/TestService/Add?n1=20&n2=20 and result returned by it is as follows <double xmlns="http://schemas.microsoft.com/2003/10/Serialization/">40</double>

终于让我找到了解决我的问题。使用JSON作为传送数据的方式和脚本,用于接收数据如下林:

Finally i found the solution to my problem. Im using JSON as way of communicating data and the script for receiving the data is as follows:

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


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


        });

    });     
</script>