第一节:ExtJS调用WCF系列-----实现JSON传递
首先我们打开我们的VS 新建一个Asp.Net WebApplication Project,(不要给我说新建网站,我讨厌那个东东) 命名为ExtJSAndWCFChapter1 如图:
接下来我们在该项目中新建一个实体类文件和一个AJAX—Enabled WCF SERVICE,分别命名为Employee.cs 和EmployeeService.svc
下面去ExtJS.Com网站下载一个ExtJS 2.0 ,解压缩后拷贝至Default.aspx相同目录下,并包括在项目中。如图:
下面开始编写代码:先编写Employee.cs的代码,代码如下:
接下来编写EmployeeService.cs的代码,代码如下:
现在可以编译并访问那个EmployeeService.svc文件,后面加上 UriTemplate的值:例如http://localhost:1481/EmployeeService.svc/get。会得到“Method not allowed”的提示。如果访问出现错误,请确认修改的Web.Config是否正确。
接下来编写Default.aspx的代码:代码如下
最终的运行效果:
源代码下载在这里
接下来我们在该项目中新建一个实体类文件和一个AJAX—Enabled WCF SERVICE,分别命名为Employee.cs 和EmployeeService.svc
下面去ExtJS.Com网站下载一个ExtJS 2.0 ,解压缩后拷贝至Default.aspx相同目录下,并包括在项目中。如图:
下面开始编写代码:先编写Employee.cs的代码,代码如下:
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.HtmlControls;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Xml.Linq;
usingSystem.Runtime.Serialization;
namespaceExtJSAndWCFChapter1
{
[DataContract]
publicclassEmployee
{
[DataMember]
publicGuidEmployeeID{set;get;}
[DataMember]
publicstringCnName{set;get;}
[DataMember]
publicboolSex{set;get;}
[DataMember]
publicintAge{set;get;}
[DataMember]
publicDateTimeBirthday{set;get;}
[DataMember]
publicstringEmail{set;get;}
}
}
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.HtmlControls;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Xml.Linq;
usingSystem.Runtime.Serialization;
namespaceExtJSAndWCFChapter1
{
[DataContract]
publicclassEmployee
{
[DataMember]
publicGuidEmployeeID{set;get;}
[DataMember]
publicstringCnName{set;get;}
[DataMember]
publicboolSex{set;get;}
[DataMember]
publicintAge{set;get;}
[DataMember]
publicDateTimeBirthday{set;get;}
[DataMember]
publicstringEmail{set;get;}
}
}
接下来编写EmployeeService.cs的代码,代码如下:
usingSystem;
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.ServiceModel;
usingSystem.ServiceModel.Activation;
usingSystem.ServiceModel.Web;
usingSystem.Collections.Generic;
namespaceExtJSAndWCFChapter1
{
[ServiceContract(Namespace="")]
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
publicclassEmployeeService
{
//Add[WebGet]attributetouseHTTPGET
[OperationContract]
publicvoidDoWork()
{
//Addyouroperationimplementationhere
return;
}
//Addmoreoperationshereandmarkthemwith[OperationContract]
/**////<summary>
///创建一个实体,实体由客户端传递
///</summary>
///<paramname="emp"></param>
///<returns></returns>
[OperationContract]
[WebInvoke(BodyStyle=WebMessageBodyStyle.Wrapped,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,UriTemplate="/Create")]
publicGuidCreate(Employeeemp)
{
NotNull(emp.CnName,"CnName");
returnGuid.NewGuid();
}
/**////<summary>
///获取一个实体
///</summary>
///<paramname="id"></param>
///<returns></returns>
[OperationContract]
[WebInvoke(BodyStyle=WebMessageBodyStyle.Bare,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,UriTemplate="/Get")]
publicEmployeeGet(intid)
{
if(id!=1)thrownewArgumentException("Expected1forID");
returnnewEmployee(){EmployeeID=Guid.NewGuid(),CnName="Xiaozhuang",Sex=true,Age=28,Email="[email protected]",Birthday=newDateTime(1979,02,02)};
}
/**////<summary>
///获取所有实体
///</summary>
///<returns></returns>
[OperationContract]
[WebInvoke(BodyStyle=WebMessageBodyStyle.Wrapped,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,UriTemplate="/GetAll")]
publicList<Employee>GetAll()
{
returnnewList<Employee>
{
newEmployee(){EmployeeID=Guid.NewGuid(),CnName="CnName",Sex=true,Age=28,Email="[email protected]",Birthday=newDateTime(1979,02,02)},
newEmployee(){EmployeeID=Guid.NewGuid(),CnName="CnName1",Sex=false,Age=28,Email="[email protected]",Birthday=newDateTime(1979,02,02)}
};
}
/**////<summary>
///获取num个实体
///</summary>
///<paramname="num"></param>
///<returns></returns>
[OperationContract]
[WebInvoke(BodyStyle=WebMessageBodyStyle.Bare,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,UriTemplate="/GetByNum")]
publicList<Employee>GetByNum(intnum)
{
if(num.ToString()=="")thrownewArgumentException("参数错误!");
List<Employee>emplist=newList<Employee>();
for(inti=1;i<=num;i++)
{
Employeeemp=newEmployee(){EmployeeID=Guid.NewGuid(),CnName=i+"CnName",Sex=true,Age=i*10,Email=i+"[email protected]",Birthday=newDateTime(1979,02,02)};
emplist.Add(emp);
}
returnemplist;
}
privatestaticvoidNotNull<T>(To,stringparamName)whereT:class
{
if(o==null)thrownewArgumentNullException(paramName);
}
}
}
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.ServiceModel;
usingSystem.ServiceModel.Activation;
usingSystem.ServiceModel.Web;
usingSystem.Collections.Generic;
namespaceExtJSAndWCFChapter1
{
[ServiceContract(Namespace="")]
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
publicclassEmployeeService
{
//Add[WebGet]attributetouseHTTPGET
[OperationContract]
publicvoidDoWork()
{
//Addyouroperationimplementationhere
return;
}
//Addmoreoperationshereandmarkthemwith[OperationContract]
/**////<summary>
///创建一个实体,实体由客户端传递
///</summary>
///<paramname="emp"></param>
///<returns></returns>
[OperationContract]
[WebInvoke(BodyStyle=WebMessageBodyStyle.Wrapped,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,UriTemplate="/Create")]
publicGuidCreate(Employeeemp)
{
NotNull(emp.CnName,"CnName");
returnGuid.NewGuid();
}
/**////<summary>
///获取一个实体
///</summary>
///<paramname="id"></param>
///<returns></returns>
[OperationContract]
[WebInvoke(BodyStyle=WebMessageBodyStyle.Bare,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,UriTemplate="/Get")]
publicEmployeeGet(intid)
{
if(id!=1)thrownewArgumentException("Expected1forID");
returnnewEmployee(){EmployeeID=Guid.NewGuid(),CnName="Xiaozhuang",Sex=true,Age=28,Email="[email protected]",Birthday=newDateTime(1979,02,02)};
}
/**////<summary>
///获取所有实体
///</summary>
///<returns></returns>
[OperationContract]
[WebInvoke(BodyStyle=WebMessageBodyStyle.Wrapped,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,UriTemplate="/GetAll")]
publicList<Employee>GetAll()
{
returnnewList<Employee>
{
newEmployee(){EmployeeID=Guid.NewGuid(),CnName="CnName",Sex=true,Age=28,Email="[email protected]",Birthday=newDateTime(1979,02,02)},
newEmployee(){EmployeeID=Guid.NewGuid(),CnName="CnName1",Sex=false,Age=28,Email="[email protected]",Birthday=newDateTime(1979,02,02)}
};
}
/**////<summary>
///获取num个实体
///</summary>
///<paramname="num"></param>
///<returns></returns>
[OperationContract]
[WebInvoke(BodyStyle=WebMessageBodyStyle.Bare,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,UriTemplate="/GetByNum")]
publicList<Employee>GetByNum(intnum)
{
if(num.ToString()=="")thrownewArgumentException("参数错误!");
List<Employee>emplist=newList<Employee>();
for(inti=1;i<=num;i++)
{
Employeeemp=newEmployee(){EmployeeID=Guid.NewGuid(),CnName=i+"CnName",Sex=true,Age=i*10,Email=i+"[email protected]",Birthday=newDateTime(1979,02,02)};
emplist.Add(emp);
}
returnemplist;
}
privatestaticvoidNotNull<T>(To,stringparamName)whereT:class
{
if(o==null)thrownewArgumentNullException(paramName);
}
}
}
主要就是这一句 [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Create")]
意思就是说这个方法传递输入和输出参数都是Json形式,并且可以用后面加Create的形式来访问该方法,至于前面那个BodyStyle = WebMessageBodyStyle.Wrapped是什么意思留着下节详细说明
接下来修改Web.Config文件,其实只是是把<enableWebScript /> 替换为<webHttp/>代码如下(一部分)
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behaviorname="ExtJSAndWCFChapter1.EmployeeServiceAspNetAjaxBehavior">
<!--<enableWebScript/>-->
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironmentaspNetCompatibilityEnabled="true"/>
<services>
<servicename="ExtJSAndWCFChapter1.EmployeeService">
<endpointaddress=""behaviorConfiguration="ExtJSAndWCFChapter1.EmployeeServiceAspNetAjaxBehavior"binding="webHttpBinding"contract="ExtJSAndWCFChapter1.EmployeeService"/>
</service>
</services>
</system.serviceModel>
<behaviors>
<endpointBehaviors>
<behaviorname="ExtJSAndWCFChapter1.EmployeeServiceAspNetAjaxBehavior">
<!--<enableWebScript/>-->
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironmentaspNetCompatibilityEnabled="true"/>
<services>
<servicename="ExtJSAndWCFChapter1.EmployeeService">
<endpointaddress=""behaviorConfiguration="ExtJSAndWCFChapter1.EmployeeServiceAspNetAjaxBehavior"binding="webHttpBinding"contract="ExtJSAndWCFChapter1.EmployeeService"/>
</service>
</services>
</system.serviceModel>
现在可以编译并访问那个EmployeeService.svc文件,后面加上 UriTemplate的值:例如http://localhost:1481/EmployeeService.svc/get。会得到“Method not allowed”的提示。如果访问出现错误,请确认修改的Web.Config是否正确。
接下来编写Default.aspx的代码:代码如下
<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="ExtJSAndWCFChapter1._Default"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>UntitledPage</title>
<linkrel="stylesheet"type="text/css"href="ExtJS/resources/css/ext-all.css"/>
<!--GC-->
<!--LIBS-->
<scripttype="text/javascript"src="ExtJS/adapter/ext/ext-base.js"></script>
<scripttype="text/javascript"src="ExtJS/ext-all-debug.js"></script>
<scripttype="text/javascript"src="ExtJS/ext-all.js"></script>
<!--ENDLIBS-->
<scripttype="text/javascript"language="javascript">
Ext.onReady(function(){
//设置Content-Type为application/json形式
Ext.lib.Ajax.defaultPostHeader='application/json';
//访问失败的统一回调函数
varonFailure=function(r,opts)
{
Ext.get("errors").insertHtml('afterend','<br/><br/>'+r.responseText,false);
}
//客户端创建一个实体
varrequest={
emp:{CnName:'xiaozhuang',
Sex:1,
Age:28,
Birthday:'/Date(62831853071)/',
Email:'[email protected]'
}
}
Ext.Ajax.request({
url:'/EmployeeService.svc/Create',//要访问的方法地址
method:'POST',
params:Ext.util.JSON.encode(request),//把输入参数进行JSON编码
success:function(response,options){Ext.get('create-p').update(response.responseText);},//输出方法返回结果
failure:onFailure
});
Ext.Ajax.request({
url:'/EmployeeService.svc/Get',
method:'POST',
params:Ext.util.JSON.encode(1),
success:function(response,options){Ext.get('get-p').update(response.responseText);},
failure:onFailure
});
Ext.Ajax.request({
url:'EmployeeService.svc/GetAll',
method:'POST',
success:function(response,options){Ext.get('getall-p').update(response.responseText);},
failure:onFailure
});
Ext.Ajax.request({
url:'EmployeeService.svc/GetByNum',
method:'POST',
params:Ext.util.JSON.encode(8),
success:function(response,options){Ext.get('GetByNum-p').update(response.responseText);},
failure:onFailure
});
});
</script>
</head>
<body>
<formid="form1"runat="server">
<div>
<h3>
Create:</h3>
<pid="create-p">
</p>
<h3>
Get:</h3>
<pid="get-p">
</p>
<h3>
GetAll:</h3>
<pid="getall-p">
</p>
<h3>
GetByNum:</h3>
<pid="GetByNum-p">
</p>
<pid="errors">
</p>
</div>
</form>
</body>
</html>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>UntitledPage</title>
<linkrel="stylesheet"type="text/css"href="ExtJS/resources/css/ext-all.css"/>
<!--GC-->
<!--LIBS-->
<scripttype="text/javascript"src="ExtJS/adapter/ext/ext-base.js"></script>
<scripttype="text/javascript"src="ExtJS/ext-all-debug.js"></script>
<scripttype="text/javascript"src="ExtJS/ext-all.js"></script>
<!--ENDLIBS-->
<scripttype="text/javascript"language="javascript">
Ext.onReady(function(){
//设置Content-Type为application/json形式
Ext.lib.Ajax.defaultPostHeader='application/json';
//访问失败的统一回调函数
varonFailure=function(r,opts)
{
Ext.get("errors").insertHtml('afterend','<br/><br/>'+r.responseText,false);
}
//客户端创建一个实体
varrequest={
emp:{CnName:'xiaozhuang',
Sex:1,
Age:28,
Birthday:'/Date(62831853071)/',
Email:'[email protected]'
}
}
Ext.Ajax.request({
url:'/EmployeeService.svc/Create',//要访问的方法地址
method:'POST',
params:Ext.util.JSON.encode(request),//把输入参数进行JSON编码
success:function(response,options){Ext.get('create-p').update(response.responseText);},//输出方法返回结果
failure:onFailure
});
Ext.Ajax.request({
url:'/EmployeeService.svc/Get',
method:'POST',
params:Ext.util.JSON.encode(1),
success:function(response,options){Ext.get('get-p').update(response.responseText);},
failure:onFailure
});
Ext.Ajax.request({
url:'EmployeeService.svc/GetAll',
method:'POST',
success:function(response,options){Ext.get('getall-p').update(response.responseText);},
failure:onFailure
});
Ext.Ajax.request({
url:'EmployeeService.svc/GetByNum',
method:'POST',
params:Ext.util.JSON.encode(8),
success:function(response,options){Ext.get('GetByNum-p').update(response.responseText);},
failure:onFailure
});
});
</script>
</head>
<body>
<formid="form1"runat="server">
<div>
<h3>
Create:</h3>
<pid="create-p">
</p>
<h3>
Get:</h3>
<pid="get-p">
</p>
<h3>
GetAll:</h3>
<pid="getall-p">
</p>
<h3>
GetByNum:</h3>
<pid="GetByNum-p">
</p>
<pid="errors">
</p>
</div>
</form>
</body>
</html>
最终的运行效果:
源代码下载在这里