• Calling WCF Services using jQuery 不及格的程序员


    Calling WCF Services using jQuery

    Introduction

    This article illustrates how to call Windows Communication Foundation (WCF) services from your jQuery client code, and points out where special care is needed. Before you start reading and following this article, first read this blog entry which describes how to create a WCF service: Create, Host and Consume a WCF Service.

    Step 1

    Once you are done with creating the WCF service, you need to specify the attributes on the server type class for ASP.NET compatibility mode, so that the WCF service works as a normal ASMX service and supports all existing ASP.NET features. By setting compatibility mode, the WCF service will have to be hosted on IIS and communicate with its client application using HTTP.

    Read more about this in detail here: WCF Web HTTP Programming Object Model.

    The following line of code sets ASP.NET compatibility mode

    [AspNetCompatibilityRequirements(RequirementsMode 
        = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service : IService
    {
        // Your code comes here
    }

    Service.cs

    [AspNetCompatibilityRequirements(RequirementsMode 
        = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service : IService
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
    
    
        public string[] GetUser(string Id)
        { 
            return new User().GetUser(Convert.ToInt32(Id));
        }
    }
    
    public class User
    {
    
        Dictionary<int, string> users = null;
        public User()
        {
            users = new Dictionary<int, string>();
            users.Add(1, "pranay");
            users.Add(2, "Krunal");
            users.Add(3, "Aditya");
            users.Add(4, "Samir");
        }
    
        public string[] GetUser(int Id)
        {
            var user = from u in users
                       where u.Key == Id
                       select u.Value;
    
            return user.ToArray<string>();
        }
    
    }

    Step 2

    Next you need to specify attributes at operation level in the service contract file for each method or operation. To do this, decorate the method with WebInvoke, which marks a service operation as one that responds to HTTP requests other than GET. Accordingly, your operational level code in the contract file will be as follows:

    [OperationContract]
    [OperationContract]
    [WebInvoke(Method = "POST", 
     BodyStyle = WebMessageBodyStyle.Wrapped,
     ResponseFormat = WebMessageFormat.Json)]
    string[] GetUser(string Id);

    As you can see in the code, sub-attributes having values to support calling via jQuery are marked with Method=post, so data gets posted to the service via a POST method.

    ResponseFormat = WebMessageFormat.Json indicates that data is returned in JSON format.

    IService.cs

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
         ResponseFormat = WebMessageFormat.Json)]
        string GetData(int value);
    
        [OperationContract]
        [WebInvoke(Method = "POST", 
         BodyStyle = WebMessageBodyStyle.Wrapped, 
         ResponseFormat = WebMessageFormat.Json)]
        string[] GetUser(string Id);
    }

    Step 3

    You need to change the default configuration created by Visual Studio in Web.Config file for WCF services, so that it works with the HTTP protocol request send by jQuery client code.

    <system.serviceModel>
      <behaviors>
       <serviceBehaviors>
        <behavior name="ServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
       </serviceBehaviors>
       <endpointBehaviors>
        <behavior name="EndpBehavior">
         <webHttp/>
        </behavior>
       </endpointBehaviors>
      </behaviors>
      <services>
       <service behaviorConfiguration="ServiceBehavior" name="Service">
        <endpoint address="" binding="webHttpBinding" 
    
            contract="IService" behaviorConfiguration="EndpBehavior"/>
       </service>
      </services>
    </system.serviceModel>

    As you can see in above config file, the EndPoint setting is changed, and EndPointBehaviors added to support WEBHTTP requests.

    Note: Endpoint settings done in the config works in conjunction with the WebInvoke attribute of the operation and the compatibility attribute set in ServiceType to support HTTP requests sent by jQuery.

    Step 4

    To consume a web service using jQuery, that is to make a call to the WCF service, you either use jQuery.ajax() or jQuery.getJSON(). In this article I used the jQuery.ajax()method.

    To set the request, first define a variable. This will be helpful when you are calling multiple methods and creating a different js file to call the WCF service.

    <script type="text/javascript">
    
        var Type;
        var Url;
        var Data;
        var ContentType;
        var DataType;
        var ProcessData;

    The following function initializes variables which are defined above to make a call to the service.

    function WCFJSON() {
        var userid = "1";
        Type = "POST";
        Url = "Service.svc/GetUser";
        Data = '{"Id": "' + userid + '"}';
        ContentType = "application/json; charset=utf-8";
        DataType = "json"; varProcessData = true; 
        CallService();
    }

    The CallService function sends requests to the service by setting data in $.ajax.

    // Function to call WCF  Service       
    function CallService() {
        $.ajax({
            type: Type, //GET or POST or PUT or DELETE verb
            url: Url, // Location of the service
            data: Data, //Data sent to server
            contentType: ContentType, // content type sent to server
            dataType: DataType, //Expected data format from server
            processdata: ProcessData, //True or False
            success: function(msg) {//On Successfull service call
                ServiceSucceeded(msg);
            },
            error: ServiceFailed// When Service call fails
        });
    }
    
    function ServiceFailed(result) {
        alert('Service call failed: ' + result.status + '' + result.statusText);
        Type = null;
        varUrl = null;
        Data = null; 
        ContentType = null;
        DataType = null;
        ProcessData = null;
    }

    Note: The following code checks the result.GetUserResult statement, so your result object gets the property your service method name + Result. Otherwise, it will give an error like object not found in Javascript.

    function ServiceSucceeded(result) {
        if (DataType == "json") {
            resultObject = result.GetUserResult;
            
            for (i = 0; i < resultObject.length; i++) {
                alert(resultObject[i]);
            }
                
        }
            
    }
    
    function ServiceFailed(xhr) {
        alert(xhr.responseText);
    
        if (xhr.responseText) {
            var err = xhr.responseText;
            if (err)
                error(err);
            else
                error({ Message: "Unknown server error." })
        }
        
        return;
    }
    
    $(document).ready(
        function() {
            WCFJSON();
        }
    );
    </script>

    Summary

    It is easy to call a WCF service from your client code you; just need to set your WCF service to serve requests through the HTTP protocol and set your client to consume it via the HTTP protocol.


    如何:使用 WCF Web HTTP 编程模型创建返回任意数据的服务

    有时,开发人员必须完全控制从服务操作返回数据的方式。 当服务操作必须由 WCF 不支持的格式返回数据时,这是这种情况。 本主题讨论如何使用 WCF WEB HTTP 编程模型来创建此类服务。 此服务具有一个返回流的操作。

    实现服务协定

    1. 定义服务协定。 该协定名为 IImageServer,具有一个名为 GetImage 的方法,该方法返回 Stream

      [ServiceContract]  
          public interface IImageServer  
          {  
              [WebGet]  
              Stream GetImage(int width, int height);  
          }  
      

      因为该方法将返回Stream、 WCF 假定该操作具有完全控制从服务操作返回的字节数和其应用任何格式设置为返回的数据。

    2. 实现服务协定。 该协定只有一个操作:GetImage。 此方法生成一个位图,再以 .jpg 格式将其保存到 MemoryStream。 随后,操作将该流返回给调用方。

      public class Service : IImageServer  
         {  
             public Stream GetImage(int width, int height)  
             {  
                 Bitmap bitmap = new Bitmap(width, height);  
                 for (int i = 0; i < bitmap.Width; i++)  
                 {  
                     for (int j = 0; j < bitmap.Height; j++)  
                     {  
                         bitmap.SetPixel(i, j, (Math.Abs(i - j) < 2) ? Color.Blue : Color.Yellow);  
                     }  
                 }  
                 MemoryStream ms = new MemoryStream();  
                 bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);  
                 ms.Position = 0;  
                 WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";  
                 return ms;  
             }  
         }  
      

      请注意代码的倒数第二行:WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";

      这会设置内容类型标头"image/jpeg"。 虽然此示例演示如何返回 .jpg 文件,但可以对其进行修改,以任意格式返回所需的任意类型的数据。 该操作必须检索或生成数据,然后将它写入流。

    承载服务

    1. 创建用于承载服务的控制台应用程序。

      class Program  
      {  
          static void Main(string[] args)  
          {  
          }   
      }  
      
    2. 在 Main 方法中创建一个变量以保存服务的基址。

      string baseAddress = "http://" + Environment.MachineName + ":8000/Service";  
      
    3. 为服务创建一个 ServiceHost 实例,指定服务类和基址。

      ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));  
      
    4. 使用 WebHttpBinding 和 WebHttpBehavior 添加一个终结点。

      host.AddServiceEndpoint(typeof(IImageServer), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());  
      
    5. 打开服务主机。

      host.Open()  
      
    6. 等待用户按 Enter 终止服务。

      Console.WriteLine("Service is running");  
      Console.Write("Press ENTER to close the host");  
      Console.ReadLine();  
      host.Close();  
      

    使用 Internet Explorer 调用原始服务

    1. 运行该服务,您应看到来自它的以下输出。 Service is running Press ENTER to close the host

    2. 打开 Internet Explorer 并键入 http://localhost:8000/Service/GetImage?width=50&height=40,您应看到一个黄色矩形,有蓝色对角线穿过其中心。

    示例

    下面列出了此主题的完整代码。

    using System;  
    using System.Collections.Generic;  
    using System.Text;  
    using System.ServiceModel;  
    using System.ServiceModel.Web;  
    using System.ServiceModel.Description;  
    using System.IO;  
    using System.Drawing;  
      
    namespace RawImageService  
    {  
        // Define the service contract  
        [ServiceContract]  
        public interface IImageServer  
        {  
            [WebGet]  
            Stream GetImage(int width, int height);  
        }  
      
        // implement the service contract  
        public class Service : IImageServer  
        {  
            public Stream GetImage(int width, int height)  
            {  
                // Although this method returns a jpeg, it can be  
                // modified to return any data you want within the stream  
                Bitmap bitmap = new Bitmap(width, height);  
                for (int i = 0; i < bitmap.Width; i++)  
                {  
                    for (int j = 0; j < bitmap.Height; j++)  
                    {  
                        bitmap.SetPixel(i, j, (Math.Abs(i - j) < 2) ? Color.Blue : Color.Yellow);  
                    }  
                }  
                MemoryStream ms = new MemoryStream();  
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);  
                ms.Position = 0;  
                WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";  
                return ms;  
            }  
        }  
      
        class Program  
        {  
            static void Main(string[] args)  
            {  
                string baseAddress = "http://" + Environment.MachineName + ":8000/Service";  
                ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));  
                host.AddServiceEndpoint(typeof(IImageServer), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());  
                host.Open();  
                Console.WriteLine("Service is running");  
                Console.Write("Press ENTER to close the host");  
                Console.ReadLine();  
                host.Close();  
      
            }  
        }  
    }  
    

    编译代码

    • 编译示例代码时,请引用 System.ServiceModel.dll 和 System.ServiceModel.Web.dll。

    请参阅


    如何:创建启用了 AJAX 的 WCF 服务和 ASP.NET 客户端访问服务

    本主题演示如何使用 Visual Studio 来创建启用了 AJAX 的 Windows Communication Foundation (WCF) 服务和 ASP.NET 客户端访问该服务。

    创建 ASP.NET Web 应用

    1. 打开 Visual Studio。

    2. 从文件菜单中,选择新建 > 项目

    3. 在中新的项目对话框中,展开已安装 > Visual C# > Web类别,然后选择ASP.NET Web 应用程序 (.NET Framework) 。

    4. 将项目命名SandwichServices然后单击确定。

    5. 在中新的 ASP.NET Web 应用程序对话框中,选择空,然后选择确定。

      Visual Studio 中的 ASP.NET web 应用程序类型对话框

    添加 web 窗体

    1. 右键单击 SandwichServices 项目中的解决方案资源管理器,然后选择添加 > 新项。

    2. 在中添加新项对话框中,展开已安装 > Visual C# > Web类别,然后选择Web 窗体模板。

    3. 接受默认名称 (WebForm1),然后选择添加。

      WebForm1.aspx中打开源视图。

    4. 添加以下标记内的 <正文> 标记:

      HTML
      <input type="button" value="Price of 3 sandwiches" onclick="Calculate()"/>
      <br />
      <span id="additionResult"></span>
      

    创建启用了 AJAX 的 WCF 服务

    1. 右键单击 SandwichServices 项目中的解决方案资源管理器,然后选择添加 > 新项。

    2. 在中添加新项对话框中,展开已安装 > Visual C# > Web类别,然后选择WCF 服务 (ajax) 模板。

      在 Visual Studio 中的 WCF 服务 (ajax) 项模板

    3. 将服务命名CostService ,然后选择添加。

      CostService.svc.cs在编辑器中打开。

    4. 在服务中实现该操作。 将以下方法添加到 CostService 类,以计算量的三明治的成本:

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

    配置客户端访问服务

    1. 打开WebForm1.aspx文件,然后选择设计视图。

    2. 从视图菜单中,选择工具箱。

    3. 展开AJAX Extensions节点和拖放ScriptManager拖到窗体。

    4. 回到源视图中,添加以下代码之间 <ScriptManager > 标记,以指定 WCF 服务的路径:

      XML
      <Services>
         <asp:ServiceReference Path="~/CostService.svc" />
      </Services>
      
    5. 添加 Javascript 函数的代码Calculate()。 将以下代码中的放置head web 窗体的部分:

      HTML
      <script type="text/javascript">
      
          function Calculate() {
              CostService.CostOfSandwiches(3, onSuccess);
          }
      
          function onSuccess(result) {
              var myres = $get("additionResult");
              myres.innerHTML = result;
          }
      
      </script>
      

      此代码调用 CostService 来计算三个三明治的价格的方法,并在调用的范围显示结果additionResult。

    运行程序

    请确保WebForm1.aspx具有焦点,,然后按启动按钮以启动 web 客户端。 按钮有一个绿色三角形和内容类似于IIS Express (Microsoft Edge) 。 或者,可以按F5。 单击3 三明治的价格按钮以生成预期的输出为"3.75"。

    示例代码

    以下是中的完整代码CostService.svc.cs文件:

    C#
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    
    namespace SandwichServices
    {
        [ServiceContract(Namespace = "")]
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        public class CostService
        {
            [OperationContract]
            public double CostOfSandwiches(int quantity)
            {
                return 1.25 * quantity;
            }
        }
    }
    

    下面是完整的内容WebForm1.aspx页:

    ASP.NET (C#)
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SandwichServices.WebForm1" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript">
    
            function Calculate() {
                CostService.CostOfSandwiches(3, onSuccess);
            }
    
            function onSuccess(result) {
                var myres = $get("additionResult");
                myres.innerHTML = result;
            }
    
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
            </div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
                <Services>
                    <asp:ServiceReference Path="~/CostService.svc" />
                </Services>
            </asp:ScriptManager>
    
            <input type="button" value="Price of 3 sandwiches" onclick="Calculate()" />
            <br />
            <span id="additionResult"></span>
        </form>
    </body>
    </html>
    

     

  • 相关阅读:
    ASP.NET MVC中 CKeditor 通过两种方法向后台传值以及编码、乱码问题
    如何解析<textarea>标签中的html代码
    ASP.NET MVC中,后台向前台传递多个对象(表)的方法
    ASP.NET MVC 环境下CKeditor 的配置以及用jQuery进行数据存取操作
    jquery下 动态显示jqGrid 以及jqGrid的属性设置容易出现的问题
    ASP.NET MVC 中 CKeditor.js的正确引用
    关于有道词典的一个小错误
    ASP.NET MVC 标签绑定传值及后台获取并进行修改操作
    每天学点GDB 6
    每天学点GDB 9
  • 原文地址:https://www.cnblogs.com/ioriwellings/p/11422540.html
Copyright © 2020-2023  润新知