用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(, , )};
}
}
}
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');
}
点击Get Value按钮:



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


总结:WCF Service的配置文件中的endpoint的binding要使用webHttpBinding,endpointBehavior要设置成enableWebScript。
WebForm中要在ScriptManager中添加WCF Service的引用。

用JavaScript调用WCF Service的更多相关文章
- jquery或者JavaScript调用WCF服务的方法
/****************************************************************** * Copyright (C): 一心堂集团 * CLR版本: ...
- JavaScript调用wcf服务,并且处理返回的字典集合
1.第一步创建wcf服务的方法 using System;using System.Collections.Generic;using System.Linq;using System.Runtime ...
- 如何创建一个AJAX-Enabled WCF Service
原创地址:http://www.cnblogs.com/jfzhu/p/4041638.html 转载请注明出处 前面的文章中介绍过<Step by Step 创建一个WCF Servi ...
- Step by Step 创建一个WCF Service
原创地址:http://www.cnblogs.com/jfzhu/p/4025448.html 转载请注明出处 (一)创建WCF Service (1)创建WCF Service类库 创建一个Cla ...
- ASP.NET4.0中JavaScript脚本调用Web Service 方法
环境:VS2019 .net 4.0 framework 根据教材使用ScriptManager在JavaScript中调用Web service 时,失败.现将过程和解决方法记录如下: 1.定义W ...
- 实现jquery.ajax及原生的XMLHttpRequest跨域调用WCF服务的方法
关于ajax跨域调用WCF服务的方法很多,经过我反复的代码测试,认为如下方法是最为简便的,当然也不能说别人的方法是错误的,下面就来上代码,WCF服务定义还是延用上次的,如: namespace Wcf ...
- 学习调用WCF服务的各种方法
1.开发工具调用WCF 这中方法很方便也很简单,很多工作VS就帮我们完成了.相信大家也不会对这种方法陌生.这里简单提一下.打开VS,在项目中添加服务引用: 在config中自动声明了有关服务的节点信息 ...
- jQuery调用WCF服务传递JSON对象
下面这个示例使用了WCF去创建一个服务端口从而能够被ASP.Net页面通过jQuery的AJAX方法访问,我们将在客户端使用Ajax技术来 与WCF服务进行通信.这里我们仅使用jQuery去连接Web ...
- [转]学习 WCF (6)--学习调用WCF服务的各种方法
转自:http://www.cnblogs.com/gaoweipeng/archive/2009/07/26/1528263.html 作者这篇博文写得很全面. 根据不同的情况,我们可以用不同的方法 ...
随机推荐
- ubuntu14 备份
备份命令 # tar cvpjf backup.tar.bz2 –exclude=/proc –exclude=/lost+found –exclude=/backup.tar.bz2 –exclud ...
- axure的一些注意事项
1. 不要轻易用中继器的 载入时 事件, 感觉存在bug 2. 元件在显示和隐藏的动画过程中,不要去取他的x,y值,有几率会取成0,也不要去获取它的尺寸,只有在动画完成后才能获得 3. 装着一个中继器 ...
- 嵌入式Linux学习入门:控制LED灯
记录自己linux学习过程,让自己能够一直坚持下去 1.原理图分析: nLED_1, nLED_2, nLED_4, 给低电平则对应LED灯亮,高电平则对应LED灯灭, S3C2440芯片GPF4-G ...
- JavaScript高级程序设计-(3) 变量、作用域和内存问题
传递参数 ECMAScript所有函数参数都是按值传递的,即使对象在函数内部修改了参数的值,原始的引用任然不变,局部对象在函数执行完毕后被销毁
- hdu2662
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2662 莫名其妙写了一个题,感觉还是很有价值的记录一下. 题目大意:给两个互质的数,求用无限个它们不能组 ...
- mac linux 删除一个文件下边所有文件和文件夹
sudo rm -r -f 目录
- 控制Storyboard播放zz
<Grid Width="300" Height="460"> <Grid.RowDefinitions> <RowDefinit ...
- Mac使用总结
显示隐藏文件 终端输入:defaults write com.apple.finder AppleShowAllFiles -bool true; KillAll Finder 添加SSHKey Ma ...
- 原生AJAX封装
var ajaxHelper = { /*1.0 浏览器兼容的方式创建异步对象*/ makeXHR: function () { //声明异步对象变量 var xmlHttp = false; //声 ...
- bzoj1927最小费用最大流
其实本来打算做最小费用最大流的题目前先来点模板题的,,,结果看到这道题二话不说(之前打太多了)敲了一个dinic,快写完了发现不对 我当时就这表情→ =_=你TM逗我 刚要删突然感觉dinic的模 ...