WCF的确不错,它大大地简化和统一了服务的开发。但也有不少朋友问过我,说是在非.NET客户程序中,有何很好的方法直接调用服务吗?还有就是在AJAX的代码中(js)如何更好地调用WCF服务呢?

我首先比较推荐的是可以通过页面静态方法等方式来转接对WCF的服务。尤其是WCF是属于别的网站的一部分的时候。

但今天我要讲解一下,如果和WCF在一个网站内部,那么js脚本应该如何更好地调用WCF呢?或者说,为了支持js更好地访问,WCF服务在设计的时候应该注意什么呢?

1. 创建服务

2. 修改接口

为了做演示,我们将默认的那个Operation修改一下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
namespace WebApplication1
{
// 注意: 如果更改此处的接口名称 "INorthwindService",也必须更新 Web.config 中对 "INorthwindService" 的引用。
[ServiceContract]
public interface INorthwindService
{
[OperationContract]
[WebGet(UriTemplate="HelloWorld")]
string HelloWorld();
}
}

注意,我们这里加了一个WebGet的Attribute,这将允许WCF服务直接通过地址调用

3. 实现服务

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text; namespace WebApplication1
{
// 注意: 如果更改此处的类名 "NorthwindService",也必须更新 Web.config 中对 "NorthwindService" 的引用。
public class NorthwindService : INorthwindService
{ #region INorthwindService 成员 public string HelloWorld()
{
return "Hello,world";
} #endregion
}
}

这里的实现依然是我最喜欢的HelloWorld

4. 修改配置文件(web.config),要支持直接通过WebGet的方法调用WCF服务,必须用一个特殊的binding,是webHttpBinding

 <system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="WebApplication1.NorthwindServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="test">
<webHttp/>
</behavior>
</endpointBehaviors>

</behaviors>
<services>
<service behaviorConfiguration="WebApplication1.NorthwindServiceBehavior"
name="WebApplication1.NorthwindService">
<endpoint address="" binding="webHttpBinding" contract="WebApplication1.INorthwindService" behaviorConfiguration="test">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>

上面的粗斜体部分是要添加或者修改的

5. 浏览该服务

我们看到,通过这样的地址就可以实现调用了。默认情况下,它返回的数据格式是XML的

6. 修改合约,让它返回json数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
namespace WebApplication1
{
// 注意: 如果更改此处的接口名称 "INorthwindService",也必须更新 Web.config 中对 "INorthwindService" 的引用。
[ServiceContract]
public interface INorthwindService
{
[OperationContract]
[WebGet(UriTemplate="HelloWorld",ResponseFormat=WebMessageFormat.Json)]
string HelloWorld();
}
}

7. 在客户端脚本js中实现对WCF的调用

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!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 runat="server">
<title></title> <script src="jquery-1.3.2-vsdoc.js" type="text/javascript"></script> <script type="text/javascript" language="javascript">
$(function() {
$("#helloWorld").click(function() {
var url = "NorthwindService.svc/HelloWorld";
$.ajax({
url: url,
dataType: "json",
success: function(result) {
alert(result);
}
});
});
});
</script> </head>
<body>
<form id="form1" runat="server">
<input type="button" value="HelloWorld" id="helloWorld" />
</form>
</body>
</html>

这样是不是就很容易了呢?

8. 实现复杂数据的处理

注意下面代码中的黑斜体部分

服务合约

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
namespace WebApplication1
{
// 注意: 如果更改此处的接口名称 "INorthwindService",也必须更新 Web.config 中对 "INorthwindService" 的引用。
[ServiceContract]
public interface INorthwindService
{
[OperationContract]
[WebGet(UriTemplate="HelloWorld",ResponseFormat=WebMessageFormat.Json)]
string HelloWorld(); [OperationContract]
[WebGet(UriTemplate = "GetEmployee?id={id}", ResponseFormat = WebMessageFormat.Json)]
Employee GetEmployeeInfo(int id);

} public class Employee {
public int ID { get; set; }
public string Name { get; set; }
}

}
服务实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text; namespace WebApplication1
{
// 注意: 如果更改此处的类名 "NorthwindService",也必须更新 Web.config 中对 "NorthwindService" 的引用。
public class NorthwindService : INorthwindService
{ #region INorthwindService 成员 public string HelloWorld()
{
return "Hello,world";
} #endregion #region INorthwindService 成员 public Employee GetEmployeeInfo(int id)
{
return new Employee
{
ID = id,
Name = "chenxizhang"
};
}
#endregion
}
}
页面代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!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 runat="server">
<title></title> <script src="jquery-1.3.2-vsdoc.js" type="text/javascript"></script> <script type="text/javascript" language="javascript">
$(function() {
$("#helloWorld").click(function() {
var url = "NorthwindService.svc/HelloWorld";
$.ajax({
url: url,
dataType: "json",
success: function(result) {
alert(result);
}
});
}); $("#getEmployee").click(function() {
var url = "NorthwindService.svc/GetEmployee?id=1";
$.ajax({
url: url,
dataType: "json",
success: function(result) {
alert(result.Name);
}
}); });

});
</script> </head>
<body>
<form id="form1" runat="server">
<input type="button" value="HelloWorld" id="helloWorld" />
<input type="button" value="Get Employee" id="getEmployee" />
</form>
</body>
</html>
没错,就是这么清晰易懂的代码。
那么,如何实现POST,或者PUT以及DELETE这种请求呢?
9. 实现POST或者PUT,DELETE请求
服务合约
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
namespace WebApplication1
{
// 注意: 如果更改此处的接口名称 "INorthwindService",也必须更新 Web.config 中对 "INorthwindService" 的引用。
[ServiceContract]
public interface INorthwindService
{
[OperationContract]
[WebGet(UriTemplate="HelloWorld",ResponseFormat=WebMessageFormat.Json)]
string HelloWorld(); [OperationContract]
[WebGet(UriTemplate = "GetEmployee?id={id}", ResponseFormat = WebMessageFormat.Json)]
Employee GetEmployeeInfo(int id); [OperationContract]
[WebInvoke(UriTemplate = "SubmitEmployee?id={id}&Name={name}", ResponseFormat = WebMessageFormat.Json)]
ActionResult SubmitEmployee(int id, string name);

} public class Employee {
public int ID { get; set; }
public string Name { get; set; }
} public class ActionResult{
public int Code { get; set; }
public string Message { get; set; }
}

}
 
实现服务
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text; namespace WebApplication1
{
// 注意: 如果更改此处的类名 "NorthwindService",也必须更新 Web.config 中对 "NorthwindService" 的引用。
public class NorthwindService : INorthwindService
{ #region INorthwindService 成员 public string HelloWorld()
{
return "Hello,world";
} #endregion #region INorthwindService 成员 public Employee GetEmployeeInfo(int id)
{
return new Employee
{
ID = id,
Name = "chenxizhang"
};
} #endregion #region INorthwindService 成员 public ActionResult SubmitEmployee(int id, string name)
{
//这里可以将该员工提交到数据库,并且根据结果返回相应的ActionResult
//作为演示,直接返回 return new ActionResult
{
Code = 200,
Message = string.Format("你提交了一个员工,编号为:{0},姓名为:{1}", id, name)
};
}
#endregion
}
}
 
页面代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!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 runat="server">
<title></title> <script src="jquery-1.3.2-vsdoc.js" type="text/javascript"></script> <script type="text/javascript" language="javascript">
$(function() {
$("#helloWorld").click(function() {
var url = "NorthwindService.svc/HelloWorld";
$.ajax({
url: url,
dataType: "json",
success: function(result) {
alert(result);
}
});
}); $("#getEmployee").click(function() {
var url = "NorthwindService.svc/GetEmployee?id=1";
$.ajax({
url: url,
dataType: "json",
success: function(result) {
alert(result.Name);
}
}); }); $("#submitEmployee").click(function() {
var url = "NorthwindService.svc/SubmitEmployee?id=1&Name=chenxizhang";
$.ajax({
type: "POST",
url: url,
dataType: "json",
success: function(result) {
alert(result.Code + "," + result.Message);
}
});
});

});
</script> </head>
<body>
<form id="form1" runat="server">
<input type="button" value="HelloWorld" id="helloWorld" />
<input type="button" value="Get Employee" id="getEmployee" />
<input type="button" value="Submit Employee" id="submitEmployee" />
</form>
</body>
</html>
 

如何让WCF服务更好地支持Web Request和AJAX调用的更多相关文章

  1. 实现在GET请求下调用WCF服务时传递对象(复合类型)参数

    WCF实现RESETFUL架构很容易,说白了,就是使WCF能够响应HTTP请求并返回所需的资源,如果有人不知道如何实现WCF支持HTTP请求的,可参见我之前的文章<实现jquery.ajax及原 ...

  2. Ajax请求WCF服务以及跨域的问题解决

    Ajax请求WCF服务以及跨域的问题解决 这两天准备重构一下项目,准备用纯html+js做前台,然后通过ajax+WCF的方式来传递数据,所以就先研究了一下ajax访问的wcf的问题,还想到还折腾了一 ...

  3. 完全使用接口方式调用WCF 服务

    客户端调用WCF服务可以通过添加服务引用的方式添加,这种方式使用起来比较简单,适合小项目使用.服务端与服务端的耦合较深,而且添加服务引用的方式生成一大堆臃肿的文件.本例探讨一种使用接口的方式使用WCF ...

  4. 实现jquery.ajax及原生的XMLHttpRequest跨域调用WCF服务的方法

    关于ajax跨域调用WCF服务的方法很多,经过我反复的代码测试,认为如下方法是最为简便的,当然也不能说别人的方法是错误的,下面就来上代码,WCF服务定义还是延用上次的,如: namespace Wcf ...

  5. 创建WCF服务寄宿到IIS

    一.WCF简介: Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台. 整合了原有的win ...

  6. WCF入门(八)---WCF服务绑定

    WCF服务绑定是一个集合,每个元素定义了服务与客户端进行通信方式的几个元素.传输元素和一个消息编码元素各自结合两个最重要的组成部分.这里是WCF服务绑定常用的列表. 基础绑定 基础约束是由basicH ...

  7. WCF服务使用(IIS+Http)和(Winform宿主+Tcp)两种方式进行发布

    1.写在前面 刚接触WCF不久,有很多地方知其然不知其所以然.当我在[创建服务->发布服务->使用服务]这一过程出现过许多问题.如客户端找不到服务引用:客户端只在本机环境中才能访问服务,移 ...

  8. WCF服务创建到发布(SqlServer版)

    在本示例开始之前,让我们先来了解一下什么是wcf? wcf有哪些特点? wcf是一个面向服务编程的综合分层架构.该架构的项层为服务模型层. 使用户用最少的时间和精力建立自己的软件产品和外界通信的模型. ...

  9. WCF服务调用超时错误:套接字连接已中止。这可能是由于处理消息时出错或远程主机超过接收超时或者潜在的网络资源问题导致的。本地套接字超时是“00:05:30”(已解决)

    问题: 线上正式环境调用WCF服务正常,但是每次使用本地测试环境调用WCF服务时长就是出现:套接字连接已中止.这可能是由于处理消息时出错或远程主机超过接收超时或者潜在的网络资源问题导致的.本地套接字超 ...

随机推荐

  1. MyBatis框架的基本使用

    MyBatis框架简介 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名 ...

  2. ThinkPHP中的四种路由形式

    1.普通形式路由(get形式路由) 路由形式:http://网址/入库文件?m=分组&c=控制器&c=控制器&a=方法名&参数=参数 例子:http://localho ...

  3. 修饰符(动态String数组篇)--- 常用 解除疑问。

    1.无修饰符----是直接传基本类型的地址过来,并没有把基本类型的指针复制一份入栈,所以一旦修改就是修改原来的值. 2.const 修饰符 与 无修饰符一致. 3.var修饰符 与 上一致. 4.ou ...

  4. Java 从多层嵌套中访问内部类的成员

    一个内部类被嵌套多少层并不重要--它能透明地访问所有它能嵌入的外围类的所有成员 //: innerclasses/MultiNestingAccess.java // Nested classes c ...

  5. 用户说体验 | 关于阿里百川HotFix你需要了解的一些细节

    最近很火的热修复技术,无意中了解到阿里百川也在做,而且Android.iOS两端都支持,所以决定试一试.试用一段时间后,感觉还不错,主要是他们有一个团队在不断维护更新这个产品,可以看到他们的版本更新记 ...

  6. mvc的cshtml Request取不到值

    如果路径为:http://localhost:2317/food/1,这时用Request["id"]是取不到值的应该用: Request.RequestContext.Route ...

  7. JDBC连接池和DBUtils

    本节内容: JDBC连接池 DBUtils 一.JDBC连接池 实际开发中“获得连接”或“释放资源”是非常消耗系统资源的两个过程,为了解决此类性能问题,通常情况我们采取连接池技术,来共享连接Conne ...

  8. 如何解决谷歌Chrome浏览器空白页的问题

    如何解决谷歌Chrome浏览器空白页的问题   谷歌Chrome浏览器突然不打开任何网页,无论是任何站点(如http://www.baidu.com), 还是Chrome浏览器的设置页面(chrome ...

  9. 终端(terminal)、tty、shell、控制台(console)、bash之间的区别与联系

    1.终端(terminal) 终端(termimal)= tty(Teletypewriter, 电传打印机),作用是提供一个命令的输入输出环境,在linux下使用组合键ctrl+alt+T打开的就是 ...

  10. Dijkstra算法---HDU 2544 水题(模板)

    /* 对于只会弗洛伊德的我,迪杰斯特拉有点不是很理解,后来发现这主要用于单源最短路,稍稍明白了点,不过还是很菜,这里只是用了邻接矩阵 套模板,对于邻接表暂时还,,,没做题,后续再更新.现将这题贴上,应 ...