启用Ajax的wcf服务器端与客户端应用

一、先看一下程序结构图与运行测试图片如下:

1.程序结够图:
 

2.运行效果图:

点击Test按钮调用wcf方法弹出调用返回结果
 

二、实现细节:我的开发环境(VS2010,.net4版本,其他版本没有做过测试)

1.首先创建一个webapp应用程序,然后添加启用ajax的wcf服务,如图


 

然后添加一个Test方法注意为该方法添加 [OperationContract] 与  [WebGet(RequestFormat=WebMessageFormat.Json)] 标签关于WebGet标签的详细介绍参见:MSDN

其次要对该WCF类进行标签修饰:[ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [JavascriptCallbackBehavior(UrlParameterName="JsonCallBack")]
尤其注意这两个标签,关于

AspNetCompatibilityRequirements说明:

 

在应用于服务实现类时,此属性可指示该服务是否需要 ASP.NET 兼容模式,或是否支持为宿主应用程序域 (AppDomain) 启用该兼容模式。

AppDomains 宿主 服务可在两种不同的宿主模式下运行:

  • 混合传输模式(默认):在这种模式下, 服务不参与 ASP.NET HTTP 管线。 这可保证 服务行为的一致性,使其不受宿主环境和传输的影响。

  • ASP.NET 兼容模式:在这种模式下, 服务以与 ASMX 服务类似的方式参与 ASP.NET HTTP 管线。 ASP.NET 功能(例如,文件授权、URL 授权和 HTTP 会话状态)适用于在此模式下运行的 服务。

宿主模式由应用程序级配置标志 aspNetCompatibilityEnabled 控制。

<system.serviceModel>

<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

</system.serviceModel>

默认情况下,此标志为 false,因此,除非明确选择使用 兼容模式,否则 ASP.NET 服务将在混合传输模式下运行。

有关以下内容的更多信息ASP.NET 兼容模式的更多信息,请参见 serviceHostingEnvironment

使用 RequirementsMode 属性可以实现此目的。 运行时,应用程序可以通过检查静态属性 AspNetCompatibilityEnabled 的值,来检测是否启用了 ASP.NET 兼容模式。


 

JavascriptCallbackBehavior说明:

 

JSONP 是一种用于在 Web 浏览器中启用跨站点脚本支持的机制。 JSONP 涉及发送一个带有作为 URL 查询字符串参数值提供的回调函数名称的请求。 相应的服务将返回一个响应,其中带有包装在对所提供的回调函数的调用中的常规 JSON 负载(如同一行可执行代码)。

以下是用于调用某个服务的 URL 的示例:http://baseAddress/Service/RESTService?callback=functionName 在调用该服务时,该服务将使用以下 JSON 进行响应:

 
functionName({ “root”:”Something});

JavascriptCallbackBehaviorAttribute 允许开发人员指定 URL 查询字符串参数的名称来解释为回调参数。 默认值是“callback”(不区分大小写)。

到此为止wcf服务端代码部分已经结束。

2.wcf服务端Webconfig配置,先把Demo的配置文件贴上来然后一点一点解释:

 

<?xml version="1.0" encoding="utf-8"?>  
  1.   
  2. <!--  
  3.   有关如何配置 ASP.NET 应用程序的详细消息,请访问  
  4.   http://go.microsoft.com/fwlink/?LinkId=169433  
  5.   -->  
  6.   
  7. <configuration>  
  8.     <system.web>  
  9.         <compilation debug="true" targetFramework="4.0" />  
  10.       <!--添加:authentication,并设置为Forms-->    
  11.         <authentication mode="Forms"/>  
  12.     </system.web>  
  13.   
  14.     <system.serviceModel>  
  15.         <behaviors>  
  16.             <endpointBehaviors>  
  17.                 <behavior name="Wcf.demo.AjaxServiceAspNetAjaxBehavior">  
  18.                     <enableWebScript />  
  19.                 </behavior>  
  20.             </endpointBehaviors>  
  21.           <!--添加serviceBehaviors-->  
  22.           <serviceBehaviors>  
  23.             <behavior name="EnableMetadataBehaviors">  
  24.               <serviceMetadata httpGetEnabled="true"/>  
  25.               <serviceDebug includeExceptionDetailInFaults="true"/>  
  26.             </behavior>  
  27.           </serviceBehaviors>  
  28.           <!--添加serviceBehaviors:结束-->            
  29.         </behaviors>  
  30.       <!--添加bindings-->  
  31.       <bindings>  
  32.         <webHttpBinding>  
  33.           <binding name="test" crossDomainScriptAccessEnabled="true"></binding>  
  34.         </webHttpBinding>  
  35.       </bindings>  
  36.       <!--添加bindings:结束-->  
  37.         
  38.         <serviceHostingEnvironment aspNetCompatibilityEnabled="true"  
  39.             multipleSiteBindingsEnabled="true" />  
  40.         <services>  
  41.             <!--为service添加:behaviorConfiguration:元数据-->  
  42.             <service name="Wcf.demo.AjaxService" behaviorConfiguration="EnableMetadataBehaviors">  
  43.               <!--为endpoint添加:bindingConfiguration跨域-->  
  44.                 <endpoint address="" behaviorConfiguration="Wcf.demo.AjaxServiceAspNetAjaxBehavior"  
  45.                   bindingConfiguration="test"   binding="webHttpBinding" contract="Wcf.demo.AjaxService" />  
  46.             </service>  
  47.         </services>  
  48.         </services>  
  49.     </system.serviceModel>  
  50. </configuration>  


2.1添加 <authentication mode="Forms"/>身份验证采用Forms验证

 

2.2 添加服务端行为配置节

      <!--添加serviceBehaviors-->
          <serviceBehaviors>
            <behavior name="EnableMetadataBehaviors">
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
          </serviceBehaviors>
          <!--添加serviceBehaviors:结束-->         

关于serviceMetadata的介绍,摘自msdn

 

此配置元素允许您控制服务的元数据发布功能。为了防止无意中泄露潜在的敏感服务元数据,Windows Communication Foundation (WCF) 服务的默认配置将禁用元数据发布。默认情况下此行为是安全的,但也意味着您无法使用元数据导入工具(例如 Svcutil.exe)生成调用服务所需的客户端代码,除非在配置中显式启用服务的元数据发布行为。使用此配置元素,可以为服务启用此发布行为。

有关配置此行为的详细代码示例,请参见Metadata Publishing Behavior

利用可选的 httpGetBindinghttpsGetBinding 属性,您可以配置用于通过 HTTP GET(或 HTTPS GET)检索元数据的绑定。如果未指定这两个属性,则根据情况使用相应的默认绑定(采用 HTTP 时为 HttpTransportBindingElement,采用 HTTPS 时为 HttpsTransportBindingElement)进行元数据检索。请注意:不能将这些属性用于内置 WCF 绑定。仅支持具有支持 IReplyChannel 的内部绑定元素的绑定。此外,绑定的 MessageVersion 属性必须为 None

为了降低服务被恶意使用者滥用的可能性,可以使用 SSL over HTTP (HTTPS) 机制来确保传输的安全。为此,必须首先将一个适合的 X.509 证书绑定到承载该服务的计算机上的特定端口。(有关更多信息,请参见 Working with Certificates.)然后,将此元素添加到服务配置,并将 httpsGetEnabled 特性设置为 true。最后,将 httpsGetUrl 属性设置为服务元数据终结点的 URL.

2.3为wcf添加webHttpBinding配置

   <!--添加bindings-->
      <bindings>
        <webHttpBinding>
          <binding name="test" crossDomainScriptAccessEnabled="true"></binding>
        </webHttpBinding>
      </bindings>
      <!--添加bindings:结束-->

注意要启用跨域设置:crossDomainScriptAccessEnabled="true"

2.4为service添加behaviorConfiguration配置信息以及为endpoint添加bindingConfiguration跨域配置信息

  <!--为service添加:behaviorConfiguration:元数据-->
            <service name="Wcf.demo.AjaxService" behaviorConfiguration="EnableMetadataBehaviors">
              <!--为endpoint添加:bindingConfiguration跨域-->
                <endpoint address="" behaviorConfiguration="Wcf.demo.AjaxServiceAspNetAjaxBehavior"
                  bindingConfiguration="test"   binding="webHttpBinding" contract="Wcf.demo.AjaxService" />
            </service>
        </services>
 

至此服务端开发完毕。

三、客户端开发

创建一个test.html页面然后添加jquery类库引用 <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>,Demo中用的是jquery1.4.1min版本

贴一些html页代码很简单,不做解释了

 

<html xmlns="http://www.w3.org/1999/xhtml">  
  1. <head>  
  2.     <title></title>  
  3.     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  4.     <script type="text/javascript">  
  5.         $(function () {  
  6.                         $("#btnTest").bind("click", function () {  
  7.                             var url = "http://localhost:7348/AjaxService.svc/Test?JsonCallBack=?&";  
  8.                             $.getJSON(url, { "value": "小甜心,300站" }, function (msg) {  
  9.                                 alert(msg)  
  10.                             });  
  11.                         });  
  12.   
  13.               
  14.         });  
  15.     </script>  
  16. </head>  
  17. <body>  
  18. <input  id="btnTest" value="Test" type="button"/>  
  19. </body>  
  20. </html>  
posted on 2012-10-19 14:13  _Totti_  阅读(307)  评论(0)    收藏  举报