如何使用ASP.NET AJAX访问Web Services/WCF Services

本文探讨了如何在AJAX-enabled Web应用中使用客户端脚本调用ASP.NET WebServices(.asmx)和Windows Communication Foundation (WCF) services(.svc),包括自定义服务的创建与调用,以及使用HTTP POST和GET动词进行请求的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Web Services

使用客户端script调用ASP.NET Web services (.asmx)和Windows Communication Foundation(WCF) services(.svc).脚本引用是自动添加到页面上的,并且他们自动产生Web service proxy类,你就从这里使用客户端脚本调用Web service.

你还能访问ASP.NET Web Servicce 不使用ASP.NET AJAX 服务端控件(如,如果你使用不同的Web开发环境).这样做,在页面上你能动手包括引用Microsoft AJAX Library,引用脚本文件,并且相应自己的Web service.在运行时,ASP.NET产生代理类调用服务.


ASP.NET Web services是组件下的一个方法调用HTTP.在下面你学习怎样创建一个Web service和怎样使用客户端脚本在一个AJAX-enabled Web application中调用WebSerice.

Using Web Services in ASP.NET AJAX

其实 ASP.NET AJAX使用客户端脚本调用服务,这个服务中既有自己定义的服务也有构建在应用程序服务.应用程序服务在ASP.NET AJAX 中也有所他提供,并包括authentication, roles, and profile services.

在ASP.NET Web Services也自定义创建Web Services,或Windows Communication Foundation (WCF) services (.svc services).


一:使用场景:

你使用WCF和ASP.NET有下面case:

    a:如果你已经创建WCF服务,你能添加进入终端的AJAX-enabled Web pages中允许访问服务,
    b:如果你已经创建ASP.NET Web (.asmx) services,你能修改他们允许使用脚本访问同样的服务.
    c:如果你要使用ASP.NET AJAX Web pages上使用脚本访问你自己创建的自定义服务.你能像WCF service或an ASP.NET Web service样实现它.
    d:你能使用ASP.NET application构建的services去访问AJAX-enabled Web page用户的authentication, roles, and profile的信息.


二:背景

    在页面上的交流使用通过一个Web service communication层,使用AJAX技术产生Web service调用.数据在客户端和服务端异步交换,特别是在JSON格式上.

    (1)Client-Server Communication for AJAX Clients
    在AJAX-enabled Web pages上,浏览器向服务端制造一个初始化请求,并且为数据并发异步请求Web services.客户交流的主要元素是从服务端下载proxy类和core client-script library.服务端交流的主要元素是handlers和自定义services.下面图片显示这些元素在服务端与客户端之间交流被调用的情况.



    (2)AJAX Client Architecture
    浏览器被使用proxy类调用Web service方法.一个proxy(代理)类是在服务端自动产生的并且在页面加载时下载到浏览器.这个代理类提供一个客户端对象呈现暴露一个Web serice的方法.

    调用一个Web service方法,客户端脚本调用相应的代理类方法.而且调用是异步的,是通过XMLHTTP对象.
   
    Web service communication layer包括允许代理类产生服务调用的脚本类型库.

在代理服务类里面的代码和在核心Web Service交流层隐藏XMLHTTP的复杂性和不同浏览器的复杂性.简化客户端脚本调用Web service.

    (1)使用HTTP POST verb调用Web services.一个POST请求已经有一个包括浏览器发送到服务端的数据的主体.它没有大小的限制.因此,当数据大小超过一个GET 请求的大小时候你仍然能使用POST请求.在客户端serializes请求进入JSON格式并且发送像POST数据样的到服务端.服务端deserializesJSON数据进入.NET Framework类型并制造真正的Web service调用.在这个期间响应,服务端serializes或返回值和并返回到客户端,在客户端通过deserializes他们成为JavaScript objects.

    (2)使用HTTP GET verb调用Web services.类似一个POST请求的功能.
        a:这个cilent使用一个查询字符串发送到参数到服务端.
        b:一个GET请求能一次只能调用调用一个Web service方法要使用ScriptMethodAttribute attribute标记一下.
        c:数据大小被限制就在于浏览允许URL的长度上.

下面是显示ASP.NET AJAX client 架构:

 

客户端架构包括在library里面的Web service communication layer和为服务下载到页面上的代理类.下面是单个元素的详细介绍:

    a:Custom Service Proxy Classes:这些由服务端自动产生并下载到客户端脚本组成的.代理类为在页面上使用WCF和ASMX中提供一个对象(那是,他们在ScriptManager control 的ServiceReferences中为每一个项提供元素).
    b:Authentication Proxy Class.Authentication Proxy Class由服务端的authentication 应用程序服务产生.它允许用户登陆或注销通过JavaScript做这件事情不需要往返服务器端.
    C:Role Proxy Class:RoleService proxy Class是由server roles application service产生.它允许你分组用户和将用户分组成一个单元,通过JavaScript做这件事情不需要往返服务器端.这能使用在授权或拒绝访问服务端资源.

    D:Profile Proxy Class:ProfileService Class.是由server ProfileService application service产生.它允许你当前用户的资料信息到达客户端通过JavaScript做这件事情不需要往返服务器端.
    E:Page Methods Proxy Class:为在ASP.NET页面上客户端脚本调用静态方法提供底层架构.如果他们是Web service方法.

    F:Web Service Communication Layer.这是一个库包括客户端脚本类型.这些类型允许浏览器与服务器端使用服务交流.他们还保护客户端应用程序设置的复杂性.和维护客户端和服务端的异步交流.他们封装浏览器提供异步兼容的XMLHTTP对象.并且授权使用得客户端应用程序不受浏览器的约束.下面主要Web service communication layer元素.

           (1)WebRequest: 提供客户端功能产生一个Web ruquest.
           (2)WebRequestManager: 这个是使用关联执行对象的WebRequest object管理Web requests 发行的流程.
            (3)XmlHttpExecutor:使用浏览器的XMLHTTP制造一个异步网络请求.
            (4)JSON Serialization:这是serializes JavaScript objects成为JSON格式.使用JavaScript eval function就能Deserialization.
            (5)XML Serialization:Web service communication layer支持XML serialization 对SOAP请求 Web services和从一个JSON请求一个Web service返回XML类型.


三:事例


    在下面是怎样调用ASP.NET和WCF服务.从客户端脚本调用应用程序服务是提供在其他部分.
   

(1)使用AJAX调用Web Service方法.

.NET Framework 授权你使用客户端浏览器异步调用ASP.NET Web services(.asmx)方法.在页面能调用基于服务端方法不需要postback和不刷新页面.因为只有数据在客户端与服务端传输.
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html >

    
<head id="Head1" runat="server">
        
<style type="text/css">
            body 
{}{  font: 11pt Trebuchet MS;
                    font-color
: #000000;
                    padding-top
: 72px;
                    text-align
: center }


            .text 
{}{ font: 8pt Trebuchet MS }
        
</style>

        
<title>Simple Web Service</title>

            
<script type="text/javascript">

            
// This function calls the Web Service method.  
            function GetServerTime()
            
{
                Samples.AspNet.ServerTime.GetServerTime(OnSucceeded);
            }


            
// This is the callback function that
            // processes the Web Service return value.
            function OnSucceeded(result)
            
{
                
var RsltElem = document.getElementById("Results");
                RsltElem.innerHTML 
= result;
            }


        
</script>

    
</head>

    
<body>
        
<form id="Form1" runat="server">
         
<asp:ScriptManager runat="server" ID="scriptManager">
                
<Services>
                    
<asp:ServiceReference path="ServerTime.asmx" />
                
</Services>
            
</asp:ScriptManager>
            
<div>
                
<h2>Server Time</h2>
                    
<p>Calling a service that returns the current server time.</p>

                    
<input id="EchoButton" type="button" 
                        value
="GetTime" onclick="GetServerTime()" />
            
</div>
        
</form>

        
<hr/>

        
<div>
            
<span id="Results"></span>
        
</div>   

    
</body>

</html>
下面是WebService
<%@ WebService Language="C#" Class="Samples.AspNet.ServerTime" %>

using System;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

namespace Samples.AspNet
{

    [WebService(Namespace 
= "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo 
= WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    
public class ServerTime : System.Web.Services.WebService
    
{

        [WebMethod]
        
public string GetServerTime()
        
{
            
return String.Format("The server time is {0}."
                DateTime.Now);

        }


    }


}


(2)从AJAX客户端产生HTTP请求   

你还能最低级别的使用客户端脚本调用Web service.如果你有管理communication layer或调查来服务端的发送数据.你就使用WebRequest类去调用Web服务.

下面是怎样使用WebRequest对象实现GET和POST Web请求连接详细指定的URLs.
// ConnectingEndPoints.js

var resultElement;

function pageLoad()
{
    resultElement 
= $get("ResultId");
}


// This function performs a GET Web request.
function GetWebRequest()
{
    alert(
"Performing Get Web request.");

    
// Instantiate a WebRequest.
    var wRequest = new Sys.Net.WebRequest();

    
// Set the request URL.      
    wRequest.set_url("getTarget.htm");
    alert(
"Target Url: getTarget.htm");

    
// Set the request verb.
    wRequest.set_httpVerb("GET");

    
// Set the request callback function.
    wRequest.add_completed(OnWebRequestCompleted);

    
// Clear the results area.
    resultElement.innerHTML = "";

    
// Execute the request.
    wRequest.invoke();  
}


// This function performs a POST Web request.
function PostWebRequest()
{
    alert(
"Performing Post Web request.");

    
// Instantiate a WebRequest.
    var wRequest = new Sys.Net.WebRequest();

    
// Set the request URL.      
    wRequest.set_url("postTarget.aspx");
    alert(
"Target Url: postTarget.aspx");

    
// Set the request verb.
    wRequest.set_httpVerb("POST");

    
// Set the request handler.
    wRequest.add_completed(OnWebRequestCompleted);

    
// Set the body for he POST.
    var requestBody = 
        
"Message=Hello! Do you hear me?";
    wRequest.set_body(requestBody);
    wRequest.get_headers()[
"Content-Length"= 
        requestBody.length;

    
// Clear the results area.
   resultElement.innerHTML = "";

    
// Execute the request.
    wRequest.invoke();              
}



// This callback function processes the 
//
 request return values. It is called asynchronously 
//
 by the current executor.
function OnWebRequestCompleted(executor, eventArgs) 
{    
    
if(executor.get_responseAvailable()) 
    
{
        
// Clear the previous results. 

       resultElement.innerHTML 
= "";

        
// Display Web request status. 
       resultElement.innerHTML +=
          
"Status: [" + executor.get_statusCode() + " " + 
                    executor.get_statusText() 
+ "]" + "<br/>";

        
// Display Web request headers.
       resultElement.innerHTML += 
            
"Headers: ";

       resultElement.innerHTML 
+= 
            executor.getAllResponseHeaders() 
+ "<br/>";

        
// Display Web request body.
       resultElement.innerHTML += 
            
"Body:";

      
if(document.all)
        resultElement.innerText 
+= 
           executor.get_responseData();
      
else
        resultElement.textContent 
+= 
           executor.get_responseData();
    }


}

if (typeof(Sys) !== "#ff0000") Sys.Application.notifyScriptLoaded();


(3)Calling WCF Service Operations in AJAX


你能使用脚本异步调用调用 Windows Communication Foundation (WCF) services (.svc).下面是怎样调用Windows Communication Foundation (WCF) services
<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html  >
<head runat="server">
    
<style type="text/css">
        body 
{}{  font: 11pt Trebuchet MS;
                font-color
: #000000;
                padding-top
: 72px;
                text-align
: center }


        .text 
{}{ font: 8pt Trebuchet MS }
    
</style>
    
<title>Simple WCF Service Page</title>

</head>
<body>
    
<form id="form1" runat="server">
        
<asp:ScriptManager ID="ScriptManager1" runat="server">
            
<Services>
                
<asp:ServiceReference 
                    
Path="SimpleService.svc/ws"/>
            
</Services>
            
<Scripts>
                
<asp:ScriptReference Path="service.js" />
            
</Scripts>
        
</asp:ScriptManager>
        
        
<div>
            
<h2>Simple WCF Service</h2>
            
<input type='button' name="clickme"  value="Greetings" 
                onclick
="javascript:OnClick()" /> &nbsp; &nbsp;
            
<input type='button' name="clickme2"  value="Greetings2" 
                onclick
="javascript:OnClick2()" />
            
<hr/>
            
<div>
                
<span id="Results"></span>
            
</div> 
        
</div>

    
</form>
</body>
</html>


var ServiceProxy;

function pageLoad()
{
    ServiceProxy 
= new ISimpleService();
    ServiceProxy.set_defaultSucceededCallback(SucceededCallback);
}


function OnClick()
{
    
// var myService = new ISimpleService();
    ServiceProxy.HelloWorld1("George");
}


function OnClick2()
{
    
var dc = new DataContractType();
    dc.FirstName 
= "George";
    dc.LastName 
= "Washington";
    ServiceProxy.HelloWorld2(dc);      
}


// This is the callback function that
//
 processes the Web Service return value.
function SucceededCallback(result, userContext, methodName)
{
    
var RsltElem = document.getElementById("Results");
    RsltElem.innerHTML 
= result + " from " + methodName + ".";
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Activation;

// This a WCF service which consists of a contract, 
// defined below as ISimpleService, and DataContractType, 
// a class which implements that interface, see SimpleService, 
// and configuration entries that specify behaviors associated with 
// that implementation (see <system.serviceModel> in web.config)

namespace Aspnet.Samples
{
    [ServiceContract()]
    
public interface ISimpleService
    
{
        [OperationContract]
        
string HelloWorld1(string value1);
        [OperationContract]
        
string HelloWorld2(DataContractType dataContractValue1);
    }


    [ServiceBehavior(IncludeExceptionDetailInFaults 
= true)]
    [AspNetCompatibilityRequirements(RequirementsMode 
= AspNetCompatibilityRequirementsMode.Allowed)]
    
public class SimpleService : ISimpleService
    
{
        
public SimpleService()
        
{ }

        
public string HelloWorld1(string value1)
        
{
            
return "Hello " + value1;
        }

        
public string HelloWorld2(DataContractType dataContractValue1)
        
{
            
return "Hello " + dataContractValue1.FirstName +
                                
" " + dataContractValue1.LastName;
        }

    }


    [DataContract]
    
public class DataContractType
    
{
        
string firstName;
        
string lastName;

        [DataMember]
        
public string FirstName
        
{
            
get return firstName; }
            
set { firstName = value; }
        }

        [DataMember]
        
public string LastName
        
{
            
get return lastName; }
            
set { lastName = value; }
        }

    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值