`
yzd
  • 浏览: 1816998 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

启用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"?>

<!--
  有关如何配置 ASP.NET 应用程序的详细消息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
      <!--添加:authentication,并设置为Forms-->  
        <authentication mode="Forms"/>
    </system.web>

    <system.serviceModel>
        <behaviors>
            <endpointBehaviors>
                <behavior name="Wcf.demo.AjaxServiceAspNetAjaxBehavior">
                    <enableWebScript />
                </behavior>
            </endpointBehaviors>
          <!--添加serviceBehaviors-->
          <serviceBehaviors>
            <behavior name="EnableMetadataBehaviors">
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
          </serviceBehaviors>
          <!--添加serviceBehaviors:结束-->          
        </behaviors>
      <!--添加bindings-->
      <bindings>
        <webHttpBinding>
          <binding name="test" crossDomainScriptAccessEnabled="true"></binding>
        </webHttpBinding>
      </bindings>
      <!--添加bindings:结束-->
      
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
            multipleSiteBindingsEnabled="true" />
        <services>
           <!--为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>
        </services>
    </system.serviceModel>
</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">
<head>
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
                        $("#btnTest").bind("click", function () {
                            var url = "http://localhost:7348/AjaxService.svc/Test?JsonCallBack=?&";
                            $.getJSON(url, { "value": "小甜心,300站" }, function (msg) {
                                alert(msg)
                            });
                        });

            
        });
    </script>
</head>
<body>
<input  id="btnTest" value="Test" type="button"/>
</body>
</html>




分享到:
评论
1 楼 abc7797005 2011-11-22  
楼主,有没有源码,发来参考参考

相关推荐

Global site tag (gtag.js) - Google Analytics