用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。
原文: 用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

 

image_thumb7

 

加载的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按钮:

image_thumb13

 

image_thumb18

image_thumb29

 

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

 

image_thumb33

 

image_thumb36

 

 

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

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

目录
相关文章
|
4月前
|
资源调度 JavaScript Linux
【Azure 应用服务】本地Node.js部署上云(Azure App Service for Linux)遇到的三个问题解决之道
【Azure 应用服务】本地Node.js部署上云(Azure App Service for Linux)遇到的三个问题解决之道
|
4月前
|
JavaScript 前端开发
【Azure Developer】在App Service上放置一个JS页面并引用msal.min.js成功获取AAD用户名示例
【Azure Developer】在App Service上放置一个JS页面并引用msal.min.js成功获取AAD用户名示例
|
4月前
|
JavaScript Windows
【Azure 应用服务】用App Service部署运行 Vue.js 编写的项目,应该怎么部署运行呢?
【Azure 应用服务】用App Service部署运行 Vue.js 编写的项目,应该怎么部署运行呢?
|
4月前
|
开发框架 JavaScript 前端开发
【Azure Developer】App Service + PubSub +JS 实现多人版黑客帝国文字流效果图
【Azure Developer】App Service + PubSub +JS 实现多人版黑客帝国文字流效果图
|
4月前
|
前端开发 JavaScript Linux
【Azure 应用服务】在Azure App Service for Linux环境中,部署的Django应用,出现加载css、js等静态资源文件失败
【Azure 应用服务】在Azure App Service for Linux环境中,部署的Django应用,出现加载css、js等静态资源文件失败
|
5月前
|
缓存 JavaScript 前端开发
JavaScript进阶 - Web Workers与Service Worker
【7月更文挑战第4天】JavaScript的Web Workers和Service Worker增强了Web性能。Web Workers处理后台多线程,减轻主线程负担,但通信有开销,受同源策略限制。Service Worker则用于离线缓存和推送通知,需管理其生命周期、更新策略,并确保安全。两者都带来了挑战,但也极大提升了用户体验。通过理解和优化,开发者能构建更高效、安全的Web应用。
146 2
|
5月前
|
缓存 前端开发 JavaScript
JavaScript进阶 - Web Workers与Service Worker
【7月更文挑战第10天】在Web开发中,Web Workers和Service Worker提升性能。Workers运行后台任务,防止界面冻结。Web Workers处理计算密集型任务,Service Worker则缓存资源实现离线支持。常见问题包括通信故障、资源限制、注册错误及缓存更新。通过示例代码展示了两者用法,并强调生命周期管理和错误处理的重要性。善用这些技术,可构建高性能的Web应用。
119 0
|
5月前
|
缓存 JavaScript 前端开发
JavaScript进阶 - Web Workers与Service Worker
【7月更文挑战第6天】JavaScript的Web Workers和Service Worker增强了浏览器的性能处理和离线功能。Web Workers处理后台计算,减轻主线程压力,但通信有开销,受同源策略限制。Service Worker则能拦截网络请求,支持离线缓存和推送通知,但其生命周期和权限管理需谨慎处理。通过理解它们的工作原理和限制,开发者能创建更流畅、更健壮的Web应用。
121 0
|
7月前
|
SQL 存储 前端开发
React&Nest.js全栈社区平台(五)——👋封装通用分页Service实现文章流与详情
React&Nest.js全栈社区平台(五)——👋封装通用分页Service实现文章流与详情
React&Nest.js全栈社区平台(五)——👋封装通用分页Service实现文章流与详情