jquery ajax调用WCF,采用System.ServiceModel.WSHttpBinding协议
采用System.ServiceModel.WSHttpBinding或者basicHttpBinding 协议。客户端就不能直接在前端通过url直接访问服务了
它是基于SOAP协议的bing,会采用WSDL、XSD语言描述服务,你可以在客户端添加服务,通过使用客户端代理调用服务
例子效果如下,点击按钮通过服务获取数据,并把数据添加到table里面

1、定义契约以及自定义类型User
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Data;
using System.Runtime.Serialization; namespace IContract
{
[ServiceContract]
[ServiceKnownType(typeof(User))] //为了客户端可以生成对应的类
public interface IContract
{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
double Add(double x, double y); [OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string Hello(string mes); [OperationContract]
[ServiceKnownType(typeof(User))]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
IList<User> getlist(); } [Serializable]
[DataContract]
[ServiceKnownType(typeof(User))] //为了客户端可以生成对应的类
public class User
{
[DataMember]
public string Name{get;set;}
[DataMember]
public int Age { get; set; }
}
}
2、实现服务
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.ServiceModel.Activation;
using System.Text;
using IContract; namespace DBService
{
public class DBService:IContract.IContract
{
public double Add(double x, double y)
{
return x+y;
} public string Hello(string mes)
{
return "holle word:" + mes;
} public IList<User> getlist()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Age",typeof(System.Int32));
dt.Rows.Add("joe", "20");
dt.Rows.Add("ethan", "25");
dt.Rows.Add("jane", "36");
IList<User> lst = dt.ToList<User>();
return lst;
}
} public static class Extension
{
public static IList<T> ToList<T>(this DataTable dt)
{
var lst = new List<T>();
var plist = new List<System.Reflection.PropertyInfo>(typeof(T).GetProperties());
foreach (DataRow item in dt.Rows)
{
T t = System.Activator.CreateInstance<T>();
for (int i = 0; i < dt.Columns.Count; i++)
{
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (info != null)
{
if (!Convert.IsDBNull(item[i]))
{
info.SetValue(t, item[i], null);
}
}
}
lst.Add(t);
}
return lst;
} } }
3、开启服务
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Description; namespace WCFHost
{
class Program
{
static void Main(string[] args)
{
StartService();
//open();
} private static void StartService()
{
try
{
ServiceHost host1 = new ServiceHost(typeof(DBService.DBService));
host1.Opened += host_Opened;
host1.Open();
Console.ReadLine();
}
catch (Exception e)
{
throw e;
}
} static void host_Opened(object sender, EventArgs e)
{
Console.WriteLine("DBService opened successful");
} //代码方式开启服务,此时要删除配置文件
static void open()
{
Uri uri = new Uri("http://localhost:8883/DBServer"); using (ServiceHost host = new ServiceHost(typeof(DBService.DBService), uri))
{
//定义元数据发布方式,此处 通过在服务所在的URL后加“?wsdl”的方式公布WSDL,可直接通过HTTP访问得到。
System.ServiceModel.Description.ServiceMetadataBehavior behavior = new System.ServiceModel.Description.ServiceMetadataBehavior();
//此处没有定义mex终结点,必须设置HttpGetEnabled为true,否则客户端无法访问服务
behavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(behavior); //添加终结点
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IContract.IContract), new WSHttpBinding(), string.Empty); host.Opened += host_Opened;
host.Open();
Console.ReadLine(); }
}
}
}
4、配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true"></compilation>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<serviceMetadata httpGetEnabled="true" /> <!--以wsdl方式发布,因为没有mex终结点,此处必须设置为true,-->
</behavior>
</serviceBehaviors>
<endpointBehaviors>
</endpointBehaviors>
</behaviors>
<services>
<!--注意此处name必须与第三步服务的命名空间一致-->
<service behaviorConfiguration="metadataBehavior" name="DBService.DBService">
<endpoint address="" binding="wsHttpBinding" contract="IContract.IContract" ></endpoint>
<host>
<baseAddresses>
<add baseAddress="http://127.0.0.1:8883/DBServer"/>
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
5、客户端添加服务,注意点,因为WCF默认 .NET collections 对象会以数组传递,为了传递我们自定义的List<User>,
需要在引用服务时设置DataType的collection type为System.Collections.Generic.List
可以在添加时,通过高级选项设置,对于已有的可以通过服务配置设置


添加服务会自动生成客户端代理及配置文件,如下:
<?xml version="1.0"?>
<configuration> <system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web> <system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IContract" />
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://127.0.0.1:8883/DBServer" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IContract" contract="ServiceReference1.IContract"
name="WSHttpBinding_IContract">
<identity>
<userPrincipalName value="xiaochun-zhai@mercer.com" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
6、后端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls; namespace WebAjax
{
public partial class WebForm1 : System.Web.UI.Page
{ [WebMethod]
public static string SayHello()
{
return "Hello Ajax!";
} [WebMethod]
public static IList<ServiceReference1.User> getlist()
{
ServiceReference1.ContractClient client = new ServiceReference1.ContractClient();
IList<ServiceReference1.User> lst = client.getlist();
return lst;
}
}
}
7、前端代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebAjax.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="js/jquery-1.8.3.min.js"></script>
<script>
//1、调用后台方法SayHello
$(function () {
$("#btnOK").click(function () {
$.ajax({
//要用post方式
type: "Post",
//方法所在页面和方法名
url: "WebForm1.aspx/SayHello",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//返回的数据用data.d获取内容
alert(data.d);
},
error: function (err) {
alert(err);
}
}); //禁用按钮的提交
return false;
});
}); //2、调用后台方法获取数据添加到table后面
$(function () {
$("#BtnGetList").click(function () {
$.ajax({
//要用post方式
type: "Post",
//方法所在页面和方法名
url: "WebForm1.aspx/getlist",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//返回的数据用data.d获取内容
var html = "";
$.each(data.d, function (index, item) {
var name = item.Name;
var age = item.Age;
html += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
});
$("table tr:eq(0)").after(html);
},
error: function (err) {
alert(err);
}
}); //禁用按钮的提交
return false;
});
}); </script>
</head>
<body>
<div>
<button id="btnOK">SayHello to backend</button>
<button id="BtnGetList">GetList from backend</button>
<br />
<br />
<table id="mytable">
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
</table>
<br />
<br /> </div>
</body>
</html>
8、 源代码
9、参考
webHttpBinding、basicHttpBinding和wsHttpBinding区别
jquery ajax调用WCF,采用System.ServiceModel.WSHttpBinding协议的更多相关文章
- WCF入门教程(四)通过Host代码方式来承载服务 一个WCF使用TCP协议进行通协的例子 jquery ajax调用WCF,采用System.ServiceModel.WebHttpBinding System.ServiceModel.WSHttpBinding协议 学习WCF笔记之二 无废话WCF入门教程一[什么是WCF]
WCF入门教程(四)通过Host代码方式来承载服务 Posted on 2014-05-15 13:03 停留的风 阅读(7681) 评论(0) 编辑 收藏 WCF入门教程(四)通过Host代码方式来 ...
- jquery ajax调用WCF,采用System.ServiceModel.WebHttpBinding
Jquery ajax调用WCF服务 例子效果如下:原界面 点击按钮GetList get后,通过指定的Url获取数据添加到table 新建一个控制台项目,添加IContract.cs,DBServi ...
- JQuery Ajax调用WCF实例以及遇到的问题
1.遇到的最多的问题就是跨域问题,这个时间需要我们添加如下代码解决跨域的问题 第一步:在服务类加Attribute [AspNetCompatibilityRequirements(Requireme ...
- Jquery Ajax调用aspx页面方法
Jquery Ajax调用aspx页面方法 在asp.net webform开发中,用jQuery ajax传值一般有几种玩法 1)普通玩法:通过一般处理程序ashx进行处理: 2)高级玩法:通过as ...
- Jquery Ajax调用aspx页面实例
目前,我会的几种asp.net界面与后台代码交互方式有几种: 1.webform+服务器控件交互: 2.webform+jquery+ajax+一般处理程序交互: 3.webform+jquery+a ...
- jquery.ajax请求aspx和ashx的异同 Jquery Ajax调用aspx页面方法
1.jquery.ajax请求aspx 请求aspx的静态方法要注意一下问题: (1)aspx的后台方法必须静态,而且添加webmethod特性 (2)在ajax方法中contentType必须是“a ...
- Jquery ajax调用webservice总结
jquery ajax调用webservice(C#)要注意的几个事项: 1.web.config里需要配置2个地方 <httpHandlers> <remove verb ...
- Jquery Ajax 调用 WebService
原文:http://www.cnblogs.com/andiki/archive/2010/05/17/1737254.html jquery ajax调用webservice(C#)要注意的几个事项 ...
- JQuery ajax调用asp.net的webMethod
本文章转载:http://www.cnblogs.com/zengxiangzhan/archive/2011/01/16/1936938.html 在vs2010中,用JQuery ajax调用as ...
随机推荐
- linux下添加分区并挂载目录、卸载并删除分区
添加分区并挂载目录 Linux的硬盘识别: 一般使用”fdisk -l”命令可以列出系统中当前连接的硬盘 设备和分区信息.新硬盘没有分区信息,则只显示硬盘大小信息. 1.关闭服务器加上新硬盘 ...
- python 中面向对象编程的几个概念
Python super() 函数 super() 函数是用于调用父类(超类)的一个方法. super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会 ...
- 科幻大片中那些牛X代码真相
在<黑客帝国>中,救世主Neo的队友通过屏幕上"1"和"0"构成的数据流,就能看到鲜活的画面,这应该算是科幻大片中对代码最极致的表现了.其他科幻电影 ...
- Android实现圆形的图片边角
ImageView没有边角圆化的设置,但是可以通过代码设置实现.一个国外的码农写的方法. 效果: 地址:http://www.curious-creature.org/2012 代码: package ...
- CentOS 7.0 安装 ZCS 8.6.0
简介 Zimbra的核心产品是Zimbra协作套件(Zimbra Collaboration Suite,简称ZCS).除了它的核心功能是电子邮件和日程安排服务器,当然还包括许多其它的功能,就象是下一 ...
- 纯 html 以及 js 多域名跳转
<!--将以下的 endv.cn 改成要跳转的域名-->第一种:单域名的跳转 1:域名在服务器端跳转 Response.Redirect(http://endv.cn) Response. ...
- ThinkPHP3.2 新bug ReadHtmlCache 支持不区分大写和小写的函数
报错提示: Fatal error: Function name must be a string in D:\wwwroot\zbphp.com\ThinkPHP\Library\Behavior\ ...
- ZH奶酪:Ubuntu启动/重启/停止apache服务
Start Apache 2 Server /启动apache服务 # /etc/init.d/apache2 start or $ sudo /etc/init.d/apache2 start Re ...
- Hessian整合Spring
含实例源码博客推荐:http://blog.csdn.net/julyness/article/details/49023581 简介: Hessian是一个简单的连接Web服务的二进制协议. 客户端 ...
- PyQt5教程——介绍(1)
PyQt5教程阅读须知 “PyQt5教程”系列若不做明显提示,默认翻译自zetcode. 有需要翻译精度的朋友可以自行阅读英文文档. 如果本系列博文侵犯了您的合法权益,请在博客中留下评论或联系:che ...