ASP.NET Ajax调用WCF服务的代码示例

 本文的主要内容是通过ASP.NET Ajax调用WCF服务的代码示例。开发环境是:.NET Framework 3.5 Beta 2+Visual Studio 2005。

  准备:

  1、安装.NET Framework 3.5 Beta 2。

  ASP.NET Ajax调用WCF服务需要.NET Framework 3.5 Beta 2中的System.Web.Extensions.dll(3.5.0.0),System.ServiceModel.Web.dll支持。

  开始我安装的是.NET Framework 3.5 June 2007 Community Technology Preview (CTP),走了一些弯路。

  2、安装Visual Studio 2005 extensions for .NET Framework 3.0 (WCF & WPF)。

  3、检查IIS是否有.svc到c:/windows/microsoft.net/framework/v2.0.50727/aspnet_isapi.dll的映射,如果没有,建立映射,建立时取消“检查文件是否存在”的选择。

  开始:

  1、在VS 2005中新建一个Web Site项目。

  添加web.config,将改为。

  2、在该项目中添加一个WCF Service,命名为CNBlogsWCFService.svc。

  3、修改App_Code中CNBlogsWCFService.cs的代码:


[ServiceContract(Namespace = "http://www.cnblog.com/")] 
  public interface ICNBlogsWCFService 
  { 
  [OperationContract] 
  string AddToFavorites(string blogID, string postID); 
  } 
  public class CNBlogsWCFService : ICNBlogsWCFService 
  { 
  public string AddToFavorites(string blogID, string postID) 
  { 
  return string.Format("收藏成功!BlogID:{0},PostID:{1}", blogID, postID); 
  } 
  }

 

  如果想进一步了解上述代码,请参考:

  1.   Artech:[原创]我的WCF之旅(1):创建一个简单的WCF程序
  2.   Bruce Zhang:Windows Communication Foundation入门(Part Two)

  4、修改CNBlogsWCFService.svc的代码:

  增加:

Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory。

 

  改为:

 

<%@ ServiceHost Language="C#" Debug="true" Service="CNBlogsWCFService" CodeBehind="~/App_Code/CNBlogsWCFService.cs" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"%><%@ ServiceHost Language="C#" Debug="true" Service="CNBlogsWCFService" CodeBehind="~/App_Code/CNBlogsWCFService.cs" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"%>

 

  Factory是.NET Framework 3.5 Beta 2中增加的,而我们用的是Visual Studio 2005 extensions for .NET Framework 3.0,所以要手动加上。

  如果不通过Ajax调用WCF,需要设置为:Factory="System.ServiceModel.Web.WebServiceHostFactory"。

  5、开始第一次运行,访问http://localhost/AjaxWCFDemo/CNBlogsWCFService.svc,会出现如下页面:

  6、继续运行,访问http://localhost/AjaxWCFDemo/CNBlogsWCFService.svc/js,你会看到自动生成访问WCF的客户端代理脚本。

  7、OK!服务器端的WCF已经准备好了,下面就开始客户端的访问。

  8、配置ASP.NET Ajax,在web.config中进行设置:

 

<?xml version="1.0"?>
<configuration>  
  <appSettings/>
  <connectionStrings/>
  <system.web>
    <compilation debug="false">
      <assemblies>
        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>
    <authentication mode="Forms" />
    <httpHandlers>
      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
    </httpHandlers>
    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </httpModules>
  </system.web>
</configuration>

 

  注意:要设置为3.5版本的System.Web.Extensions,如果使用asp.net ajax 1.0会得不到调用WCF服务返回的结果。

  9、修改default.aspx的代码:

  1)添加ScriptManager,将ServiceReference设置为:~/CNBlogsWCFService.svc。

  2)将

 

<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>

 

  改为:

 

<%@ Register Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    Namespace="System.Web.UI" TagPrefix="asp" %>

 

  2)添加调用WCF服务的代码,完整代码如下:

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"   Namespace="System.Web.UI" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Ajax WCF 演示 </title>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center" style="margin-top:50px">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="~/CNBlogsWCFService.svc" />
            </Services>
        </asp:ScriptManager>
        <a href="#" οnclick="AddToFavorites('1','2')">收藏</a><br />
        <br />
        <span style="color:Red" id="Msg"></span>

        <script type="text/javascript">
        function AddToFavorites(blogID,postID)
        {
            var wcf = new www.cnblog.com.ICNBlogsWCFService();
            wcf.AddToFavorites(blogID,postID,OnSucceeded);
        }
        function OnSucceeded(result)
        {    
            document.getElementById("Msg").innerHTML = result;         
        }   
        </script>

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

 

  10、一切就绪,体验一下Ajax调用WCF的快乐!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 我可以回答这个问题。.NET 6 可以通过使用 WebService 类来调用 Web 服务。你需要提供 Web 服务的 URL,还需要定义要调用的 Web 方法和必要的参数。然后,你可以使用 WebService 类实例的 Invoke 方法来调用 Web 方法并获取响应。 ### 回答2: 在.NET 6 中调用 Web Service 服务非常简单。可以按照以下步骤进行操作: 1. 首先,在.NET 6 项目中添加对 Web Service 的引用。可以通过右键点击项目,然后选择“添加” -> “服务引用”来完成这一步骤。 2. 在弹出的“服务引用”对话框中,输入 Web Service 的 URL。这个 URL 是指向 Web Service 的 WSDL(Web Services Description Language)文件的链接。然后点击“添加引用”按钮。 3. 在引用添加完成后,可以在代码中使用生成的代理类来调用 Web Service 的方法。代理类会自动处理与 Web Service 的通信细节,使开发变得更加简单。 4. 通过创建代理类的实例,可以直接调用 Web Service 的方法。例如,如果 Web Service 提供了一个名为“GetData”的方法,可以使用代理类实例的“GetData”方法来调用它,传入相应的参数。 5. 调用 Web Service 方法后,可以获取返回的结果。根据 Web Service 方法的定义,可能会返回一个或多个结果。可以根据具体情况进行处理。 6. 最后,记得在使用完 Web Service 后关闭代理类实例,以释放资源。 总的来说,通过在.NET 6 中添加 Web Service 引用,并使用生成的代理类实例来调用相应的方法,可以方便地与 Web Service 进行通信和交互。这为开发人员提供了一种简单快捷的方式来利用 Web Service 的强大功能。 ### 回答3: 在.NET 6中,调用Web服务有多种方式。我将介绍两种常用的方法。 首先,你可以使用.NET的内置类库`HttpClient`来调用Web服务。首先,你需要在项目中添加对`System.Net.Http`的引用。然后,可以通过以下代码创建一个`HttpClient`对象,并发送HTTP请求: ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class Program { static async Task Main(string[] args) { HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync("http://example.com/api/service"); string result = await response.Content.ReadAsStringAsync(); Console.WriteLine(result); } } ``` 在上面的示例中,我们创建了一个`HttpClient`对象,并使用`GetAsync`方法发送了一个GET请求到指定的URL。然后,我们可以通过`response.Content.ReadAsStringAsync()`方法读取响应的内容,并打印输出。 另一种方法是使用`WCF(Windows Communication Foundation)`来调用Web服务。首先,你需要在项目中添加对`System.ServiceModel`的引用。然后,你可以使用`ChannelFactory`和服务契约来创建和调用Web服务。以下是一个示例: ```csharp using System; using System.ServiceModel; public class Program { static void Main(string[] args) { BasicHttpBinding binding = new BasicHttpBinding(); EndpointAddress address = new EndpointAddress("http://example.com/api/service"); ChannelFactory<IMyService> factory = new ChannelFactory<IMyService>(binding, address); IMyService service = factory.CreateChannel(); // 调用服务方法 string result = service.MyMethod(); Console.WriteLine(result); factory.Close(); } } [ServiceContract] public interface IMyService { [OperationContract] string MyMethod(); } ``` 在上面的示例中,我们首先创建了一个`BasicHttpBinding`对象和一个`EndpointAddress`对象,它们分别用于指定绑定和服务的地址。然后,我们使用`ChannelFactory`和服务契约(即`IMyService`接口)创建了一个服务实例。最后,我们可以通过调用服务实例的方法来调用Web服务,并输出结果。 以上是.NET 6中调用Web服务的两种常见方法。你可以根据具体情况选择适合的方法来实现你的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值