使用 jQuery 消耗 WCF / ASMX / REST 服务






4.81/5 (35投票s)
本分步教程演示了如何使用 jQuery 从应用程序中消耗 WCF、ASMX 和 REST 服务。
引言
在本文中,我将解释如何使用 jQuery 消耗 WCF / ASMX 服务。本文的范围仅限于使用 jQuery 创建和消耗不同类型的服务。我已将本文按服务消耗分为七个主题。
- 使用 jQuery 调用 ASMX Web 服务
- 使用 jQuery 调用 WCF 服务并以 JSON 格式检索数据
- 使用 jQuery 调用 WCF 服务并以 XML 格式检索数据
- 使用 jQuery 调用 WCF 服务并以 JSON 格式检索数据(传递多个输入参数)和(使用 DataContract 获取多个输出对象)
- 使用 jQuery 调用 WCF 服务 [GET 方法] 并以 JSON 格式检索数据
- 使用 jQuery 调用基于 REST 的 WCF 服务
- 通过 WCF 流式传输图像并通过 HTTP GET 请求它
如果您从未听说过 jQuery、WCF 或 JSON,请在阅读本文之前先了解它们。本文的范围仅限于服务创建和消耗。
我使用 Visual Web Developer 2008 开发了这个示例。其他使用的工具:Firebug 和 HttpAnalyzer。
在下面的示例中,我使用了 jQuery 版本 1.3.2。您可以从 https://jqueryjs.cn/ 下载。本文演示了我们基于 jQuery 的浏览器应用程序如何为提供的国家检索省份。所有服务都托管在同一个 Web 应用程序中。请下载源代码自行尝试示例。
要调用服务,我们需要使用 jQuery 的 .ajax
方法,该方法会向服务器发出 XMLHttpRequest
。在下面的代码部分,我通过在属性右侧添加注释来解释要传递的关键值对属性。
<script type="text/javascript" language="javascript"
src="script/jQuery-1.3.2.min.js" "></script>
<script type="text/javascript">
var varType;
var varUrl;
var varData;
var varContentType;
var varDataType;
var varProcessData;
function CallService()
{
$.ajax({
type : varType, //GET or POST or PUT or DELETE verb
url : varUrl, // Location of the service
data : varData, //Data sent to server
contentType : varContentType, // content type sent to server
dataType : varDataType, //Expected data format from server
processdata : varProcessData, //True or False
success : function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
</script>
我已经使上述方法通用,可以用于我们即将讨论的所有不同类型的服务。
业务逻辑
下面演示的服务业务逻辑很简单。我们将国家和省份的详细信息存储在 Name Value 集合中。当请求提供国家名称时,我们会返回与之相关的省份。
public class CountryProvinceBL
{
NameValueCollection nvProvince = null;
public CountryProvinceBL()
{
nvProvince = new NameValueCollection();
nvProvince.Add("usa", "Massachusetts");
nvProvince.Add("usa", "California");
nvProvince.Add("india", "Tamil Nadu");
nvProvince.Add("india", "Karnataka");
}
public string[] GetProvince(string Country)
{ return nvProvince.GetValues(Country).ToArray();}
}
1. 使用 jQuery 调用 ASMX Web 服务
步骤 1
创建一个 Web 服务并添加以下代码
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// Below line allows the web service to be called through HTTP protocol.
[System.Web.Script.Services.ScriptService]
public class CountryProvinceWebService : System.Web.Services.WebService
{
[WebMethod]
//Business Logic returns the provinces for the supplied country
public string[] GetProvince(string Country)
{ return new CountryProvinceBL().GetProvince(Country); }
}
第二步
单击按钮时调用以下方法
function CountryProvinceWebService() {
varType = "POST";
varUrl = "service/CountryProvinceWebService.asmx/GetProvince";
//Pass country from drop down ddlCountry'
varData = '{"Country": "' + $('#ddlCountry').val() + '"}';
varContentType = "application/json; charset=utf-8";
varDataType = "json";varProcessData = true; CallService();
}
步骤 3
成功后,将调用 ServiceSucceeded
,它将使用服务器发送的值填充省份下拉列表。
function ServiceSucceeded(result) {
var ProvinceDDL = document.getElementById("ddlProvince");
for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
var resultObject = result.d; // Constructed object name will be object.d //Button
for (i = 0; i < resultObject.length; i++) {
var opt = document.createElement("option"); opt.text = resultObject[i];
ProvinceDDL.options.add(opt)
}
}
2. 使用 jQuery 调用 WCF 服务并以 JSON 格式检索数据
步骤 1
在接口 ICountryProvinceWCFService
中定义契约。
[ServiceContract]
public interface ICountryProvinceWCFService
{
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle=WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetProvince(string Country);
}
在类 CountryProvinceWCFService
中实现契约。
public class CountryProvinceWCFService : ICountryProvinceWCFService
{
// Call Business Logic to get provinces
public string[] GetProvince(string Country)
{return new CountryProvinceBL().GetProvince(Country); }
}
第二步
在 web.config 中定义配置
<servicemetadata httpgetenabled="true">
允许用户通过 Web 浏览器查看元数据并生成 WSDL 文件。- 设置
includeExceptionDetailInFaults = "true"
允许 WCF 服务抛出原始错误;这在调试应用程序时很有用。 - 将
<webhttp>
添加到终结点行为,并将webHttpBinding
添加到绑定,即可启用 WCF 的 Web 编程模型,并允许通过 Web 协议访问服务。 - 定义服务契约和服务名称。
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="CountryProvinceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="CountryProvinceBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="CountryProvinceBehavior"
name="CountryProvinceWCFService">
<endpoint address="" binding="webHttpBinding"
contract="ICountryProvinceWCFService"
behaviorConfiguration="CountryProvinceBehavior"/>
</service>
</services>
</system.serviceModel>
步骤 3
在按钮单击事件中调用 WCF 服务
function CountryProvinceWCFJSON() {
varType = "POST";
varUrl = "service/CountryProvinceWCFService.svc/GetProvince";
varData = '{"Country": "' + $('#ddlCountry').val() + '"}';
varContentType = "application/json; charset=utf-8";
varDataType = "json"; varProcessData = true; CallService();
}
服务调用成功后,将调用 ServiceSucceeded
,并将省份值添加到省份下拉列表中。
function ServiceSucceeded(result) {/
var ProvinceDDL = document.getElementById("ddlProvince");
for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
// Constructed object name will be object.[ServiceName]Result // Button 2 & 3
var resultObject = result.GetProvinceResult;
for (i = 0; i < resultObject.length; i++) {
var opt = document.createElement("option");
opt.text = resultObject[i];
ProvinceDDL.options.add(opt)
}
}
3. 使用 jQuery 调用 WCF 服务并以 XML 格式检索数据
步骤 1
在操作契约中,将 ResponseFormat
设置为 XML。
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Xml)]
string[] GetProvinceXML(string Country);
然后,实现服务
public string[] GetProvinceXML(string Country)
{ return new CountryProvinceBL().GetProvince(Country); }
第二步
在按钮单击事件中调用 WCF 服务。请确保将预期数据类型设置为 XML。
function CountryProvinceWCFXML() {
varType = "POST";
varUrl = "service/CountryProvinceWCFService.svc/GetProvinceXML";
varData = '{"Country": "' + $('#ddlCountry').val() + '"}';
varContentType = "application/json; charset=utf-8";
varDataType = "xml"; varProcessData = true; CallService();
}
使用图 1 中定义的 web.config。
步骤 3
服务调用成功后,将调用 ServiceSucceeded
,并将省份值添加到省份下拉列表中。
function ServiceSucceeded(result) {
var ProvinceDDL = document.getElementById("ddlProvince");
for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
//Below jQuery code will loop through the XML result set
$(result).find("GetProvinceXMLResult").children().each(function() {
var opt = document.createElement("option"); opt.text = $(this).text();
ProvinceDDL.options.add(opt)
});
}
4. 使用 jQuery 调用 WCF 服务并以 JSON 格式检索数据(传递多个输入参数,并使用 DataContract 获取多个输出对象)
在此示例中,Country 和 Browser 类型将作为输入参数以 JSON 格式传递给 WCF 服务。收到值后,服务将返回传递国家的省份以及关于浏览器信息的注释。
步骤 1
为服务定义 DataContract 和 ServiceContract
[DataContract]
public class CustomData
{
[DataMember]
public String BrowserInfo;
[DataMember]
public String[] ProvinceInfo;
}
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
CustomData GetProvinceAndBrowser(string Country, string Browser);
并在您的服务调用中实现契约
public CustomData GetProvinceAndBrowser(string Country, string Browser)
{
CustomData customData = new CustomData();
customData.ProvinceInfo = new CountryProvinceBL().GetProvince(Country);
if (Browser == "ie")
customData.BrowserInfo = " Did you learn to program IE 8.0";
else if (Browser == "firefox")
customData.BrowserInfo = " Mozilla rocks, try Firebug & Fiddler addon's";
else
customData.BrowserInfo = " I did not test in this browser";
return customData;
}
第二步
使用图 1 中定义的 web.config。
步骤 3
在按钮单击事件中调用 WCF 服务。请确保将预期数据类型设置为 XML。
function CountryProvinceWCFJSONMulti() {
var browser = "";
if (jQuery.browser.mozilla == true) browser="firefox"
else if(jQuery.browser.msie == true) browser = "ie"
varType = "POST";
varUrl = "service/CountryProvinceWCFService.svc/GetProvinceAndBrowser";
//We are passing multiple paramers to the service in JSON format
// {"Country" : "india", "Browser":"ie"}
varData = '{"Country": "' + $('#ddlCountry').val() +
'","Browser": "' + browser + '"}';
varContentType = "application/json; charset=utf-8";
varDataType = "json";varProcessData = true; CallService();
}
步骤 4
服务调用成功后,将调用 ServiceSucceeded
,并将省份值添加到省份下拉列表中。
function ServiceSucceeded(result) {
var ProvinceDDL = document.getElementById("ddlProvince");
for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
//WCF Service with multiple output paramaetrs //First object
var resultObject = result.GetProvinceAndBrowserResult.ProvinceInfo;
for (i = 0; i < resultObject.length; i++) {
var opt = document.createElement("option"); opt.text = resultObject[i];
ProvinceDDL.options.add(opt)
}
//Second object sent in JSON format
$("#divMulti").html(result.GetProvinceAndBrowserResult.BrowserInfo);
}
5. 使用 jQuery 调用 WCF 服务 [GET 方法] 并以 JSON 格式检索数据
这次,我们将使用 GET 动词而不是 POST 来通过 WCF 和 jQuery 检索数据。
步骤 1
我们可以使用 WebGet
属性而不是 WebInvoke
来执行操作。
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Json)]
string[] GetProvinceGET(string Country);
实现契约
public string[] GetProvinceGET(string Country)
{return new CountryProvinceBL().GetProvince(Country);}
并使用本文前面定义的 web.config。
第二步
将动词设置为 GET 而不是 POST,并将数据作为查询字符串传递。使用以下方法调用 WCF 服务。
function CountryProvinceWCFJSONGet() {
varType = "GET";
varUrl = "service/CountryProvinceWCFService.svc/" +
"GetProvinceGET?Country=" +$('#ddlCountry').val();
varContentType = "application/json; charset=utf-8";
varDataType = "json";varProcessData = false; CallService();
}
服务调用成功后,将调用 ServiceSucceeded
,并将省份值添加到省份下拉列表中。
function ServiceSucceeded(result) {
var ProvinceDDL = document.getElementById("ddlProvince");
for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
for (i = 0; i < result.length; i++) {
var opt = document.createElement("option"); opt.text = result[i];
ProvinceDDL.options.add(opt)
}
}
6. 使用 jQuery 调用基于 REST 的 WCF 服务
步骤 1
在操作契约中定义 REST 服务的 URI,并将 BodyStyle
设置为 Bare
。
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
UriTemplate = "GetProvinceREST/{Country}",
BodyStyle=WebMessageBodyStyle.Bare)]
string[] GetProvinceREST(string Country);
实现契约
public string[] GetProvinceREST(string Country)
{ return new CountryProvinceBL().GetProvince(Country); }
使用图 1 中定义的 web.config。
第二步
使用 REST 服务时,使用 GET 动词检索数据,使用 POST、PUT、DELETE 修改、添加和删除信息。
function CountryProvinceWCFREST() {
varType = "GET";
varUrl = "service/CountryProvinceWCFService.svc/" +
"GetProvinceREST/" + $('#ddlCountry').val();
varContentType = "application/json; charset=utf-8";
varDataType = "json"; varProcessData = false; CallService();
}
服务调用成功后,将调用 ServiceSucceeded
,并将省份值添加到省份下拉列表中。
function ServiceSucceeded(result) {
var ProvinceDDL = document.getElementById("ddlProvince");
for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
for (i = 0; i < result.length; i++) {
var opt = document.createElement("option"); opt.text = result[i];
ProvinceDDL.options.add(opt)
}
}
7. 通过 WCF 流式传输图像并通过 HTTP GET 请求它
步骤 1
定义契约,并将返回类型设置为 Stream
,因为我们将以 Image/JPEG 格式发送它。
[OperationContract]
[WebInvoke(Method = "GET")]
Stream GetPicture();
实现契约
public Stream GetPicture()
{
string fileName = Path.Combine(
HostingEnvironment.ApplicationPhysicalPath,"vista.jpg");
FileStream fileStream =
new FileStream(fileName, FileMode.Open, FileAccess.Read);
// Set the content type as image/ jpeg
System.ServiceModel.Web.WebOperationContext.
Current.OutgoingResponse.ContentType = "image/jpeg";
return (Stream)fileStream;
}
然后,使用我们在本文前面定义的 web.config
第二步
在按钮单击事件中,将图像元素 [image1
] 的 src
属性设置为 WCF 服务。
<img src="" id="image1" width="500" height="400" />
function ShowImage() {// Call the WCF service
$("#image1").attr('src',
'service/CountryProvinceWCFService.svc/GetPicture');
}
结论
感谢阅读本文。为了使文章更简洁,我没有深入探讨每个方面的细节。请下载源代码自行查看示例。我在 IE 7 和 Firefox 3.5 中验证了该示例。如果您对本文有任何建议/评论/疑问,请随时提出。