如何创建一个AJAX-Enabled WCF Service

 

原创地址:http://www.cnblogs.com/jfzhu/p/4041638.html

转载请注明出处

 

前面的文章中介绍过《Step by Step 创建一个WCF Service 》以及《如何使用WCF的Trace与Message Log功能》,本文介绍如何创建一个AJAX-Enabled WCF Service。

(一)创建一个WCF AJAX-enabled service

1. 打开Visual Studio 2012,创建一个ASP.NET Empty Web Application Project,命名为SandwichServices。这时Visual Studio的web.config文件内容为:

 

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
</configuration>

 

2. 添加一个AJAX-enabled WCF Service,命名为CostService.svc

 

using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SandwichServices
{
    [ServiceContract(Namespace = "SandwichServices")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CostService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }

    }
}

因为我们不打算使用TCP等HTTP之外的Protocol,所以设置为AspNetCompatibilityEnabled。

 

3. 修改Namespace ServiceContractAttribute,并添加一个CostOfSandwiches方法

 

using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SandwichServices
{
    [ServiceContract(Namespace = "SandwichServices")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CostService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }

        [OperationContract]
        public double CostOfSandwiches(int quantity)
        {
            return 1.25 * quantity;
        }
    }
}

 

4. 这时Visual Studio生成的web.config文件

 

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="SandwichServices.CostServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <services>
      <service name="SandwichServices.CostService">
        <endpoint address="" behaviorConfiguration="SandwichServices.CostServiceAspNetAjaxBehavior"
            binding="webHttpBinding" contract="SandwichServices.CostService" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

 

如果在浏览器中访问CostService.svc,得到如下错误

 

 

5. 修改web.config文件

 

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="SandwichServices.CostServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="SandwichServices.CostServiceServiceBehavior" >
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <services>
      <service name="SandwichServices.CostService" behaviorConfiguration="SandwichServices.CostServiceServiceBehavior">
        <endpoint address="" behaviorConfiguration="SandwichServices.CostServiceAspNetAjaxBehavior"
            binding="webHttpBinding" contract="SandwichServices.CostService" />
        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

 

再次在浏览器中打开CostService.svc,可以正常访问了。

 

(二)创建Client端,调用WCF Service

1. 创建一个aspx Page

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebClient.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
        function Button1_onclick() {
            var service = new SandwichServices.CostService();
            service.CostOfSandwiches(3, onSuccess, null, null);
        }

        function onSuccess(result) {
            alert(result);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p>
        <input id="Button1" type="button" value="Price for 3 Sandwiches" onclick="return Button1_onclick()" />
        </p>
    </div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="http://192.168.6.47:8080/CostService.svc" />
            </Services>
        </asp:ScriptManager>
    </form>
</body>
</html>

 

2. 在浏览器中打开该页面,然后用F12工具可以看到加载进来的JavaScript,是WCF Service生成的。

 

Fiddler

 

3. 点击按钮调用WCF Service

 

(三) 总结

WCF Service的配置文件中的endpoint的binding要使用webHttpBinding,endpointBehavior要设置成enableWebScript。

WebForm中要在ScriptManager中添加WCF Service的引用。

时间: 2024-12-25 04:24:34

如何创建一个AJAX-Enabled WCF Service的相关文章

创建一个简单的WCF程序

WCF的服务不能孤立地存在,需要寄宿于一个运行着的进程中,我们把承载WCF服务的进程称为宿主,为服务指定宿主的过程称为服务寄宿(Service Hosting).在我们的计算服务应用中,采用了两种服务寄宿方式:通过自我寄宿(Self-Hosting)的方式创建一个控制台应用作为服务的宿主(寄宿进程为Hosting.exe):通过IIS寄宿方式将服务寄宿于IIS中(寄宿进程为IIS的工作进行W3wp.exe).客户端通过另一个控制台应用模拟(进程为Client.exe).接下来,我们就一步一步来构

WCF服务二:创建一个简单的WCF服务程序

在本例中,我们将实现一个简单的计算服务,提供基本的加.减.乘.除运算,通过客户端和服务端运行在同一台机器上的不同进程实现. 一.新建WCF服务 1.新建一个空白解决方案,解决方案名称为"WCFSolution". 2.解决方案右键->添加->类库项目,类库名称为CalculateWcfService. 3.创建服务契约 WCF采用基于契约的交互方式实现了服务的自制.服务契约:是相关操作的集合.契约就是双方或多方就某个关注点达成的一种共识,是一方向另一方的一种承诺.签署了某个

Kivy A to Z -- 如何从Python创建一个基于Binder的Service及如何从Java访问Python创建的Service

<Kivy A to Z -- 如何从python代码中直接访问Android的Service> 一文中讲到了如何从python访问java的service,这一篇再来讲下如何创建一个基于Binder的Python Service以及如何从Java代码中访问这个Python创建的Service. 先来看代码,再作下解释: 接<Kivy A to Z -- 如何从python代码中直接访问Android的Service>一文,我们在相关的文件中增加代码: binder_wrap.cp

jQuery.Ajax()执行WCF Service的方法

今天有幸被召回母校给即将毕业的学弟学妹们讲我这两年的工作史,看了下母校没啥特别的变化,就是寝室都安了空调,学妹们都非常漂亮而已..好了不扯蛋了,说下今天的主题吧.这些天我在深度定制语法高亮功能的同时发现了博客园提供的一些有意思的函数,甚至有几个博客园都没用到,我也不知道怎么才能触发那些功能..打开这个js就可以看到很多好用的东西了,虽然写的不怎么样,但是至少有这些功能. ps: 推荐安装一个代码格式化的插件,否则一坨看着蛋疼.比如第一个就是 log,方便调试. www.qidian.com/Bo

ASP.NET MVC提交一个较复杂对象至WCF Service

前一篇<jQuery.Ajax()执行WCF Service的方法>http://www.cnblogs.com/insus/p/3727875.html 我们有练习在asp.net mvc应用程序中,POST 数据去wcf service并执行方法.本篇的练习是提交较复对象至wcf service执行方法.前一篇中,它只传递两个参数.如果我们平时开发,需要传递过多的参数时,那得需要写很多个参数.因此产生此篇,把较多个参数,创建为一个对象.然后只传递这个对象至wcf service即可. 下面

转载——Step by Step 创建一个 Web Service

原创地址:http://www.cnblogs.com/jfzhu/p/4022139.html 转载请注明出处 (一)创建Web Service 创建第一个项目,类型选择ASP.NET Empty Web Application 添加一个新项目 Web Service 然后再创建一个类Contact 代码分别如下. Contact.cs: [Serializable] public class Contact { private string name; public string Name

Step by Step 创建一个 Web Service

(一)创建Web Service 创建第一个项目.类型选择ASP.NET Empty Web Application 加入一个新项目 Web Service 然后再创建一个类Contact 代码分别例如以下. Contact.cs: [Serializable] public class Contact { private string name; public string Name { get { return name; } set { name = value; } } private

Step by Step 创建一个Web Service

  (一)创建Web Service 创建一个新的解决方案,第一个项目类型选择ASP.NET Empty Web Application     添加一个新项目 Web Service     然后再创建一个类Contact   代码分别如下. Contact.cs:   HelloWebService.asmx:     (二)创建客户端 下面创建一个客户端调用Web Service,检验一下是否正确.创建一个ASP.NET Empty Web Application     添加服务引用  

WCF Service Configuration Editor的使用

WCF Service Configuration Editor的使用 2014-06-13 通过WCF Service Configuration Editor的配置修改Client端 在上篇文章创建一个简单的WCF程序中, 使用WCF Service Configuration Editor工具生成XML文件来进行WCF的配置,而不是在CS文件中敲代码. 通过WCF Service Configuration Editor的配置 返回 以下是使用WCF Service Configurati

WCF Service Configuration Editor的使用【转】

原文:http://www.cnblogs.com/Ming8006/p/3772221.html 通过WCF Service Configuration Editor的配置修改Client端 参考 在上篇文章创建一个简单的WCF程序中, 通过编码的方式进行终结点的添加和服务行为的定义,但在进行真正的WCF应用开发时,一般会直接是通过配置的方式进行. 对于初学者来说,WCF的配置显得过于复杂,直接对配置文件进行手工编辑不太现实.在这种情况下,可以直接使用VS提供的配置工具WCF Service