调用WCF服务,我们一般都是中客户端的配置文件中配置好WCF服务的终结点,然后中后台代码中实例化WCF服务,然后调用其中的方法,今天给大家介绍一种,不需要配置终结点,直接中前台通过AJax方法调用WCF服务的方法。
首先我们先创建一个控制台WCF服务
契约接口:
using System.ServiceModel; using System.ServiceModel.Web; namespace Easyway.LaserControl.Contracts { [ServiceContract(Name = "ILaserControlService",Namespace = "http://www.htzn.net.cn/")] public interface ILaserControlService { [OperationContract] [WebGet] double Add(double x,double y); } }
实现类:
using System.ServiceModel.Activation; using System.ServiceModel.Web; using Easyway.LaserControl.Contracts; using System.ServiceModel; using System.ServiceModel.Channels; using System; using System.Configuration; using System.Linq; namespace Easyway.LaserControl.Services { [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")] public class LaserControlService : ILaserControlService { public double Add(double x,double y) { //获取远端信息 var ip = GetIpAddress(); if (!AllowConnect(ip)) { var msg = string.Format("IP:{0},不在允许的访问列表,禁止访问。",ip); Console.WriteLine(msg); throw new Exception(msg); } return x + y; } private string GetIpAddress() { var remote = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; return remote.Address; } public bool AllowConnect(string ip) { Tuple<long,long>[] m_IpRanges; var ipRange = ConfigurationManager.AppSettings["IpRangeFilter"]; string[] ipRangeArray; if (string.IsNullOrEmpty(ipRange) || (ipRangeArray = ipRange.Split(new char[] { ',',';' },StringSplitOptions.RemoveEmptyEntries)).Length <= 0) { throw new ArgumentException("The ipRange doesn't exist in configuration!"); } m_IpRanges = new Tuple<long,long>[ipRangeArray.Length]; for (int i = 0; i < ipRangeArray.Length; i++) { var range = ipRangeArray[i]; m_IpRanges[i] = GenerateIpRange(range); } var ipValue = ConvertIpToLong(ip); var iplist = new System.Collections.Generic.List<long>(); for (var i = 0; i < m_IpRanges.Length; i++) { var range = m_IpRanges[i]; iplist.Add(range.Item1); iplist.Add(range.Item2); } iplist = iplist.OrderBy(a => a).ToList();//我这里认为,IP地址是成对出现的。那么,判断是否是符合标准的IP,则判断是否在范围内即可,或者范围外。 for (var i = 1; i <= iplist.Count; i += 2) { var item = iplist[i]; bool isodd = i % 2 == 1; if (isodd)//是奇数,代表是从列表的偶数位。1,3,5,7,9 { var last = iplist[i - 1]; if (last <= ipValue && item >= ipValue) return true; } } return false; } private Tuple<long,long> GenerateIpRange(string range) { var ipArray = range.Split(new char[] { '-' },StringSplitOptions.RemoveEmptyEntries); if (ipArray.Length != 2) throw new ArgumentException("Invalid ipRange exist in configuration!"); return new Tuple<long,long>(ConvertIpToLong(ipArray[0]),ConvertIpToLong(ipArray[1])); } private long ConvertIpToLong(string ip) { var points = ip.Split(new char[] { '.' },StringSplitOptions.RemoveEmptyEntries); if (points.Length != 4) throw new ArgumentException("Invalid ipRange exist in configuration!"); long value = 0; long unit = 1; for (int i = points.Length - 1; i >= 0; i--) { value += unit * Convert.ToInt32( points[i]); unit *= 256; } return value; } } }
配置文件:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <behaviors> <endpointBehaviors> <behavior name="webBehavior"> <!--这里必须设置--> <!--<webHttp />--> <enableWebScript /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="MetadataBehavior"> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://192.168.1.112:8888/LaserControlService/Metadata" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="MetadataBehavior" name="Easyway.LaserControl.Services.LaserControlService"> <endpoint binding="webHttpBinding" address="http://192.168.1.112:8889/LaserControlService/web" behaviorConfiguration="webBehavior" bindingConfiguration="webBinding" contract="Easyway.LaserControl.Contracts.ILaserControlService" /> <endpoint address="http://192.168.1.112:8890/LaserControlService" binding="wsHttpBinding" bindingConfiguration="wsBinding" contract="Easyway.LaserControl.Contracts.ILaserControlService" /> <endpoint address="http://192.168.1.112:8888/LaserControlService" binding="customBinding" bindingConfiguration="asmxbinding" contract="Easyway.LaserControl.Contracts.ILaserControlService" /> </service> </services> <bindings> <customBinding> <binding name="asmxbinding"> <textMessageEncoding maxReadPoolSize="2110" maxWritePoolSize="2132" messageVersion="Soap11"/> <httpTransport /> </binding> </customBinding> <wsHttpBinding> <binding name="wsBinding"> <security mode="None"/> </binding> </wsHttpBinding> <webHttpBinding> <binding name="webBinding" crossDomainScriptAccessEnabled="true"> </binding> </webHttpBinding> </bindings> </system.serviceModel> <appSettings> <add key="IpRangeFilter" value="192.168.1.1-192.168.1.120"/> </appSettings> </configuration>
using System; using System.ServiceModel; namespace Easyway.LaserControl { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(LaserControl.Services.LaserControlService))) { host.Opened += delegate { Console.WriteLine("服务已经启动,按任意键终止服务!"); }; host.Open(); Console.Read(); } } } }
启动WCF服务:
我们创建一个客户端来调用我们的WCF服务:
<%@ Page Language="C#" AutoEventWireup="true" Codebehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <Meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script type="text/javascript" src="jquery-1.6.4.min.js"></script> <script type="text/javascript"> $(function () { $("#btnA").click(function () { var url = "http://192.168.1.112:8889/LaserControlService/web/Add?jsoncallback=?"; url += "&x=" + $("#num1").val() + "&y=" + $("#num2").val(); getData(url); }); }); function getData(url) { $.ajax({ type: "get",dataType: "json",url: url,success: function (returndata) { $("#content").html(returndata); } }); } </script> </head> <body> <form id="form1" runat="server"> Number1 <input id="num1" name="num1" type="text" style="width: 80px" /> Number2 <input id="num2" name="num2" type="text" style="width: 80px" /> <input type="button" id="btnA" value="Add" /> <br /> <div> Result</div> <div id="content"> </div> <br /> </form> </body> </html>
运行效果:
调用成功:
这样调用WCF是不是很简单呢?
原文链接:https://www.f2er.com/ajax/162870.html