用JavaScript调用WCF Service

原文:用JavaScript调用WCF Service

 

原创地址:http://www.cnblogs.com/jfzhu/p/4039604.html

转载请注明出处

 

前面介绍过《Step by Step 创建一个WCF Service》《使用WCF的Trace与Message Log功能》,本文介绍一下如何用JavaScript来调用WCF Service。

WCF Service的代码如下:

IHelloService.cs

using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace HelloService
{
    [ServiceContract(Name = "IHelloService")]
    public interface IHelloService
    {
        [OperationContract(Name="GetMessage")]
        string GetMessage(string name);

        [OperationContract]
        Employee GetEmployee(int id);
    }
}

 

HelloService.cs

using System;

namespace HelloService
{
    public class HelloService : IHelloService
    {
        public string GetMessage(string name)
        {
            return "Hello " + name;
        }

        public Employee GetEmployee(int id)
        {
            return new Employee() { Id = id, Name="Neil Klugman", Birthdate=new DateTime(1930, 1, 31)};
        }
    }
}

 

web.config文件,注意高亮部分:

 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
      <service name="HelloService.HelloService" behaviorConfiguration="metaBehavior">
        <endpoint address="" binding="webHttpBinding" contract="HelloService.IHelloService" behaviorConfiguration="ajaxServiceBehavior"></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ajaxServiceBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="metaBehavior">
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

 

创建一个客户端web application,添加一个web form,WebForm1.aspx:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="HelloWebClient.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>AJAX Service Client Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager" runat="server">
         <Services>
             <asp:ServiceReference Path="http://192.168.6.47:8080/HelloService.svc" />
         </Services>
    </asp:ScriptManager>
    <script lang="javascript" type="text/javascript">
        function GetValueFromServer() {
            var name = document.getElementById('txtValueContainer').value;
            tempuri.org.IHelloService.GetMessage(name, onSuccess, onFailure, null);
        }

        function onSuccess(result) {
            document.getElementById('labelResult').value = result;
        }

        function onFailure(result) {
            window.alert(result);
        }

    </script>
    <div>
        <input id="btnServiceCaller" type="button" value="Get Value" onclick="GetValueFromServer()"; />
        <input id="txtValueContainer" type="text" value="" />
        <input id="labelResult" type="text" value="" />
    </div>
    </form>
</body>
</html>

 

用浏览器打开WebForm1.aspx,使用Fiddler查看,因为代码里有了对WCF Service的引用

<asp:ServiceReference Path="http://192.168.6.47:8080/HelloService.svc" />

所以页面加载了JavaScript

 

 

加载的JavaScript代码为:

 

Type.registerNamespace('tempuri.org');
tempuri.org.IHelloService = function () {
    tempuri.org.IHelloService.initializeBase(this);
    this._timeout = 0;
    this._userContext = null;
    this._succeeded = null;
    this._failed = null;
}
tempuri.org.IHelloService.prototype = {
    _get_path: function () {
        var p = this.get_path();
        if (p) return p;
        else return tempuri.org.IHelloService._staticInstance.get_path();
    },
    GetMessage: function (name, succeededCallback, failedCallback, userContext) {
        /// <param name="name" type="String">System.String</param>
        /// <param name="succeededCallback" type="Function" optional="true" mayBeNull="true"></param>
        /// <param name="failedCallback" type="Function" optional="true" mayBeNull="true"></param>
        /// <param name="userContext" optional="true" mayBeNull="true"></param>
        return this._invoke(this._get_path(), 'GetMessage', false, { name: name }, succeededCallback, failedCallback, userContext);
    },
    GetEmployee: function (id, succeededCallback, failedCallback, userContext) {
        /// <param name="id" type="Number">System.Int32</param>
        /// <param name="succeededCallback" type="Function" optional="true" mayBeNull="true"></param>
        /// <param name="failedCallback" type="Function" optional="true" mayBeNull="true"></param>
        /// <param name="userContext" optional="true" mayBeNull="true"></param>
        return this._invoke(this._get_path(), 'GetEmployee', false, { id: id }, succeededCallback, failedCallback, userContext);
    }
}
tempuri.org.IHelloService.registerClass('tempuri.org.IHelloService', Sys.Net.WebServiceProxy);
tempuri.org.IHelloService._staticInstance = new tempuri.org.IHelloService();
tempuri.org.IHelloService.set_path = function (value) {
    tempuri.org.IHelloService._staticInstance.set_path(value);
}
tempuri.org.IHelloService.get_path = function () {
    /// <value type="String" mayBeNull="true">The service url.</value>
    return tempuri.org.IHelloService._staticInstance.get_path();
}
tempuri.org.IHelloService.set_timeout = function (value) {
    tempuri.org.IHelloService._staticInstance.set_timeout(value);
}
tempuri.org.IHelloService.get_timeout = function () {
    /// <value type="Number">The service timeout.</value>
    return tempuri.org.IHelloService._staticInstance.get_timeout();
}
tempuri.org.IHelloService.set_defaultUserContext = function (value) {
    tempuri.org.IHelloService._staticInstance.set_defaultUserContext(value);
}
tempuri.org.IHelloService.get_defaultUserContext = function () {
    /// <value mayBeNull="true">The service default user context.</value>
    return tempuri.org.IHelloService._staticInstance.get_defaultUserContext();
}
tempuri.org.IHelloService.set_defaultSucceededCallback = function (value) {
    tempuri.org.IHelloService._staticInstance.set_defaultSucceededCallback(value);
}
tempuri.org.IHelloService.get_defaultSucceededCallback = function () {
    /// <value type="Function" mayBeNull="true">The service default succeeded callback.</value>
    return tempuri.org.IHelloService._staticInstance.get_defaultSucceededCallback();
}
tempuri.org.IHelloService.set_defaultFailedCallback = function (value) {
    tempuri.org.IHelloService._staticInstance.set_defaultFailedCallback(value);
}
tempuri.org.IHelloService.get_defaultFailedCallback = function () {
    /// <value type="Function" mayBeNull="true">The service default failed callback.</value>
    return tempuri.org.IHelloService._staticInstance.get_defaultFailedCallback();
}
tempuri.org.IHelloService.set_enableJsonp = function (value) { tempuri.org.IHelloService._staticInstance.set_enableJsonp(value); }
tempuri.org.IHelloService.get_enableJsonp = function () {
    /// <value type="Boolean">Specifies whether the service supports JSONP for cross domain calling.</value>
    return tempuri.org.IHelloService._staticInstance.get_enableJsonp();
}
tempuri.org.IHelloService.set_jsonpCallbackParameter = function (value) { tempuri.org.IHelloService._staticInstance.set_jsonpCallbackParameter(value); }
tempuri.org.IHelloService.get_jsonpCallbackParameter = function () {
    /// <value type="String">Specifies the parameter name that contains the callback function name for a JSONP request.</value>
    return tempuri.org.IHelloService._staticInstance.get_jsonpCallbackParameter();
}
tempuri.org.IHelloService.set_path("http://192.168.6.47:8080/HelloService.svc");
tempuri.org.IHelloService.GetMessage = function (name, onSuccess, onFailed, userContext) {
    /// <param name="name" type="String">System.String</param>
    /// <param name="succeededCallback" type="Function" optional="true" mayBeNull="true"></param>
    /// <param name="failedCallback" type="Function" optional="true" mayBeNull="true"></param>
    /// <param name="userContext" optional="true" mayBeNull="true"></param>
    tempuri.org.IHelloService._staticInstance.GetMessage(name, onSuccess, onFailed, userContext);
}
tempuri.org.IHelloService.GetEmployee = function (id, onSuccess, onFailed, userContext) {
    /// <param name="id" type="Number">System.Int32</param>
    /// <param name="succeededCallback" type="Function" optional="true" mayBeNull="true"></param>
    /// <param name="failedCallback" type="Function" optional="true" mayBeNull="true"></param>
    /// <param name="userContext" optional="true" mayBeNull="true"></param>
    tempuri.org.IHelloService._staticInstance.GetEmployee(id, onSuccess, onFailed, userContext);
}
var gtc = Sys.Net.WebServiceProxy._generateTypedConstructor;
Type.registerNamespace('jfzhu.com._2014._10._16.Employee');
if (typeof (jfzhu.com._2014._10._16.Employee.Employee) === 'undefined') {
    jfzhu.com._2014._10._16.Employee.Employee = gtc("Employee:http://jfzhu.com/2014/10/16/Employee");
    jfzhu.com._2014._10._16.Employee.Employee.registerClass('jfzhu.com._2014._10._16.Employee.Employee');
}

View Code

 

点击Get Value按钮:

 

 

使用Microsoft Service Trace Viewer查看Message Log Trace:

 

 

 

 

总结:WCF Service的配置文件中的endpoint的binding要使用webHttpBinding,endpointBehavior要设置成enableWebScript。

WebForm中要在ScriptManager中添加WCF Service的引用。

时间: 2024-08-02 14:59:25

用JavaScript调用WCF Service的相关文章

我的WCF之旅(6):在Winform Application中调用Duplex Service出现TimeoutExce

我的WCF之旅(6):在Winform Application中调用Duplex Service出现TimeoutException原因和解决 几个星期之前写了一篇关于如何通过WCF进行 双向通信的文章([原创]我的WCF之旅(3):在WCF中实现双向通信(Bi-directional Communication) ),在文章中我提供了一个如果在Console Application 调用Duplex WCF Service的Sample.前几天有个网友在上面留言说,在没有做任何改动得情况下,把

我的WCF之旅(6):在Winform Application中调用Duplex Service出现TimeoutException的原因和解决方案

几个星期之前写了一篇关于如何通过WCF进行 双向通信的文章([原创]我的WCF之旅(3):在WCF中实现双向通信(Bi-directional Communication)),在文章中我提供了一个如果在Console Application 调用Duplex WCF Service的Sample.前几天有个网友在上面留言说,在没有做任何改动得情况下,把 作为Client的Console Application 换成Winform Application,运行程序的时候总是出现Timeout的错误

jQuery实现ajax调用WCF服务的方法(附带demo下载)_jquery

本文实例讲述了jQuery实现ajax调用WCF服务的方法.分享给大家供大家参考,具体如下: 关于AJAX调用WCF服务分为跨域和不跨域两种方式,今天咱们先介绍下不跨域下的调用方法.DEMO是在VS2008写的. 经过测试与研究,发现AJAX调用WCF服务必须满足以下条件 1.wcf的通讯方式必须使用webHttpBinding 2.必须设置<endpointBehaviors>节点的值 3.服务的实现必须添加标记 复制代码 代码如下: [AspNetCompatibilityRequirem

一步一步学Silverlight :在Silverlight中如何用JavaScript调用.NET代码

概述 Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言Visual Basic, Visual C#, IronRuby, Ironpython,对JSON.Web Service.WCF以及Sockets的支持等一系列新的特性.<一步一步学Silverlight 2系列>文章将从Silverlight 2基础知识.数据与通信.自定义控件.动画.图形图像等几个方面带您快速进入Silverlight 2开发. Silv

jQuery ajax调用WCF服务实例_jquery

恩,在由瘦客户端转换成胖浏览器端的"潮流"下,必然要使用JavaScript调用后台的各种服务. 屌丝所维护的产品通信都是使用的WCF服务,因此必然要学习这样的内容.借用jQuery强大的库,使用JavaScript访问WCF服务非常简便.同事研究了一个breeze库,那么屌丝就来试验一下ajax.这里把实现简单地记录以便马克一下,以后忘了就看这篇日志来作弊. 一.更改WCF服务的配置 默认情况下,WCF服务是不允许使用HTTP请求来访问的.我们需要将WCF服务的配置文件(注意如果有其

.net 下用javascript调用webservice

javascript|web .net 下用javascript调用webservice的话,要用到webservice behavior.下面以一个例子讲解之,比较简单 1 .首先,要创建一个webservice,比如 <%@ WebService Language="C#" class=MyMath %>using System;using System.Web.Services;public class MyMath {[WebMethod]public int ad

在ASP.NET Atlas中调用Web Service—处理错误

asp.net|web|错误 在本系列的上一篇(在ASP.NET Atlas中调用Web Service--介绍及简单应用)中,我们熟悉了Atlas中调用Web Service的最基础方法,但是在实际开发中,仅仅发出请求并等待返回结果是不够的,我们大都需要考虑对错误超时等的处理,也要允许用户取消操作.幸运的是,Atlas对Web Service中的Web Method的封装也充分考虑到了这些需求.让我们举一个Web Method的例子来说明,例如,对于如下的Web Method: public

在ASP.NET Atlas中调用Web Service—批量调用以提高效率

asp.net|web 对于Atlas程序,在某些情况下,我们需要在短时间内调用大量的Web Service,例如某个列表中用户快速的点击删除.这时网络带宽,稳定程度等等往往会造成较长时间的延迟.如果可以将这些调用包装成一个单一的请求,那么用户只需忍受一次网络延迟,即可得到处理的结果,也间接的提高了效率.似乎这并不是一个很容易实现的功能,但幸运的是,Atlas中内建了对批量调用Web Service的支持,您所需要的只是在程序中简单设置一下. Atlas中每个Web Service的调用请求都有

在ASP.NET Atlas中调用Web Service

asp.net|web 在前一篇文章(在ASP.NET Atlas中调用Web Service--创建Mashup调用远端Web Service(基础知识以及简单示例))中,我介绍了一些Atlas中对远程Web Service进行Mashup的基础知识,并给出了一个最基础的没有丝毫用处例子.今天再回到这个话题上,我将给出一个更复杂点的,但有一些用处的例子--Yahoo! Weather. 废话到此为止,让我们先熟悉一下Yahoo! Weather服务:Yahoo!在其网站上提供了天气预报服务(h