WCF 之 AJax前台调用WCF服务

前端之家收集整理的这篇文章主要介绍了WCF 之 AJax前台调用WCF服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

调用WCF服务,我们一般都是中客户端的配置文件中配置好WCF服务的终结点,然后中后台代码中实例化WCF服务,然后调用其中的方法,今天给大家介绍一种,不需要配置终结点,直接中前台通过AJax方法调用WCF服务的方法


首先我们先创建一个控制台WCF服务



契约接口:

  1. using System.ServiceModel;
  2. using System.ServiceModel.Web;
  3.  
  4. namespace Easyway.LaserControl.Contracts
  5. {
  6. [ServiceContract(Name = "ILaserControlService",Namespace = "http://www.htzn.net.cn/")]
  7. public interface ILaserControlService
  8. {
  9. [OperationContract]
  10. [WebGet]
  11. double Add(double x,double y);
  12.  
  13. }
  14. }

实现类:
  1. using System.ServiceModel.Activation;
  2. using System.ServiceModel.Web;
  3. using Easyway.LaserControl.Contracts;
  4. using System.ServiceModel;
  5. using System.ServiceModel.Channels;
  6. using System;
  7. using System.Configuration;
  8. using System.Linq;
  9.  
  10. namespace Easyway.LaserControl.Services
  11. {
  12. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  13. [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]
  14. public class LaserControlService : ILaserControlService
  15. {
  16. public double Add(double x,double y)
  17. {
  18. //获取远端信息
  19. var ip = GetIpAddress();
  20. if (!AllowConnect(ip))
  21. {
  22. var msg = string.Format("IP:{0},不在允许的访问列表,禁止访问。",ip);
  23. Console.WriteLine(msg);
  24. throw new Exception(msg);
  25. }
  26.  
  27. return x + y;
  28. }
  29.  
  30.  
  31. private string GetIpAddress()
  32. {
  33. var remote =
  34. OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as
  35. RemoteEndpointMessageProperty;
  36. return remote.Address;
  37. }
  38.  
  39. public bool AllowConnect(string ip)
  40. {
  41. Tuple<long,long>[] m_IpRanges;
  42. var ipRange = ConfigurationManager.AppSettings["IpRangeFilter"];
  43.  
  44. string[] ipRangeArray;
  45.  
  46. if (string.IsNullOrEmpty(ipRange)
  47. || (ipRangeArray = ipRange.Split(new char[] { ',',';' },StringSplitOptions.RemoveEmptyEntries)).Length <= 0)
  48. {
  49. throw new ArgumentException("The ipRange doesn't exist in configuration!");
  50. }
  51.  
  52. m_IpRanges = new Tuple<long,long>[ipRangeArray.Length];
  53.  
  54. for (int i = 0; i < ipRangeArray.Length; i++)
  55. {
  56. var range = ipRangeArray[i];
  57. m_IpRanges[i] = GenerateIpRange(range);
  58. }
  59.  
  60.  
  61.  
  62. var ipValue = ConvertIpToLong(ip);
  63.  
  64. var iplist = new System.Collections.Generic.List<long>();
  65. for (var i = 0; i < m_IpRanges.Length; i++)
  66. {
  67. var range = m_IpRanges[i];
  68.  
  69. iplist.Add(range.Item1);
  70. iplist.Add(range.Item2);
  71. }
  72. iplist = iplist.OrderBy(a => a).ToList();//我这里认为,IP地址是成对出现的。那么,判断是否是符合标准的IP,则判断是否在范围内即可,或者范围外。
  73. for (var i = 1; i <= iplist.Count; i += 2)
  74. {
  75. var item = iplist[i];
  76. bool isodd = i % 2 == 1;
  77. if (isodd)//是奇数,代表是从列表的偶数位。1,3,5,7,9
  78. {
  79. var last = iplist[i - 1];
  80. if (last <= ipValue && item >= ipValue)
  81. return true;
  82. }
  83.  
  84. }
  85. return false;
  86. }
  87. private Tuple<long,long> GenerateIpRange(string range)
  88. {
  89. var ipArray = range.Split(new char[] { '-' },StringSplitOptions.RemoveEmptyEntries);
  90.  
  91. if (ipArray.Length != 2)
  92. throw new ArgumentException("Invalid ipRange exist in configuration!");
  93.  
  94. return new Tuple<long,long>(ConvertIpToLong(ipArray[0]),ConvertIpToLong(ipArray[1]));
  95. }
  96.  
  97. private long ConvertIpToLong(string ip)
  98. {
  99. var points = ip.Split(new char[] { '.' },StringSplitOptions.RemoveEmptyEntries);
  100.  
  101. if (points.Length != 4)
  102. throw new ArgumentException("Invalid ipRange exist in configuration!");
  103.  
  104. long value = 0;
  105. long unit = 1;
  106.  
  107. for (int i = points.Length - 1; i >= 0; i--)
  108. {
  109. value += unit * Convert.ToInt32( points[i]);
  110. unit *= 256;
  111. }
  112.  
  113. return value;
  114. }
  115.  
  116.  
  117. }
  118. }

配置文件
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3. <system.serviceModel>
  4. <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
  5. <behaviors>
  6. <endpointBehaviors>
  7. <behavior name="webBehavior">
  8. <!--这里必须设置-->
  9. <!--<webHttp />-->
  10. <enableWebScript />
  11. </behavior>
  12. </endpointBehaviors>
  13. <serviceBehaviors>
  14. <behavior name="MetadataBehavior">
  15. <serviceMetadata httpGetEnabled="true" httpGetUrl="http://192.168.1.112:8888/LaserControlService/Metadata" />
  16. </behavior>
  17. </serviceBehaviors>
  18. </behaviors>
  19. <services>
  20. <service behaviorConfiguration="MetadataBehavior" name="Easyway.LaserControl.Services.LaserControlService">
  21. <endpoint binding="webHttpBinding" address="http://192.168.1.112:8889/LaserControlService/web" behaviorConfiguration="webBehavior" bindingConfiguration="webBinding" contract="Easyway.LaserControl.Contracts.ILaserControlService" />
  22. <endpoint address="http://192.168.1.112:8890/LaserControlService" binding="wsHttpBinding" bindingConfiguration="wsBinding" contract="Easyway.LaserControl.Contracts.ILaserControlService" />
  23. <endpoint address="http://192.168.1.112:8888/LaserControlService" binding="customBinding" bindingConfiguration="asmxbinding" contract="Easyway.LaserControl.Contracts.ILaserControlService" />
  24. </service>
  25. </services>
  26. <bindings>
  27. <customBinding>
  28. <binding name="asmxbinding">
  29. <textMessageEncoding maxReadPoolSize="2110" maxWritePoolSize="2132" messageVersion="Soap11"/>
  30. <httpTransport />
  31. </binding>
  32. </customBinding>
  33. <wsHttpBinding>
  34. <binding name="wsBinding">
  35. <security mode="None"/>
  36. </binding>
  37. </wsHttpBinding>
  38. <webHttpBinding>
  39. <binding name="webBinding" crossDomainScriptAccessEnabled="true">
  40. </binding>
  41. </webHttpBinding>
  42. </bindings>
  43. </system.serviceModel>
  44. <appSettings>
  45. <add key="IpRangeFilter" value="192.168.1.1-192.168.1.120"/>
  46. </appSettings>
  47. </configuration>

  1. using System;
  2. using System.ServiceModel;
  3.  
  4. namespace Easyway.LaserControl
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10.  
  11. using (ServiceHost host = new ServiceHost(typeof(LaserControl.Services.LaserControlService)))
  12. {
  13. host.Opened += delegate
  14. {
  15. Console.WriteLine("服务已经启动,按任意键终止服务!");
  16. };
  17.  
  18. host.Open();
  19. Console.Read();
  20. }
  21. }
  22. }
  23. }

启动WCF服务:



我们创建一个客户端来调用我们的WCF服务:



  1. <%@ Page Language="C#" AutoEventWireup="true" Codebehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
  2.  
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head id="Head1" runat="server">
  5. <Meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <title></title>
  7.  
  8. <script type="text/javascript" src="jquery-1.6.4.min.js"></script>
  9.  
  10. <script type="text/javascript">
  11. $(function () {
  12. $("#btnA").click(function () {
  13. var url = "http://192.168.1.112:8889/LaserControlService/web/Add?jsoncallback=?";
  14. url += "&x=" + $("#num1").val() + "&y=" + $("#num2").val();
  15. getData(url);
  16. });
  17. });
  18. function getData(url)
  19. {
  20. $.ajax({
  21. type: "get",dataType: "json",url: url,success: function (returndata) {
  22. $("#content").html(returndata);
  23. }
  24. });
  25. }
  26. </script>
  27.  
  28. </head>
  29. <body>
  30. <form id="form1" runat="server">
  31. Number1
  32. <input id="num1" name="num1" type="text" style="width: 80px" />
  33. Number2
  34. <input id="num2" name="num2" type="text" style="width: 80px" />
  35. <input type="button" id="btnA" value="Add" />
  36. <br />
  37. <div>
  38. Result</div>
  39. <div id="content">
  40. </div>
  41. <br />
  42. </form>
  43. </body>
  44. </html>

运行效果



调用成功:





这样调用WCF是不是很简单呢?

猜你在找的Ajax相关文章