如下内容基于WCF4.0,本文将对比讨论配置文件方案和无配置文件方案的实现方式。web
WCF4.0加入了对RESTFU和标准终结点的支持,这为实现跨域提供了简单的方式。ajax
1、有配置文件的状况:json
首先咱们先定义一个服务:跨域
[ServiceContract] public class MinitorServer { [OperationContract] public bool Test() { return true; } }
在这里我故意没有声明接口,顺便废话几句,正常状况下咱们应该定义接口去显示服务契约(servercontract)和操做契约(operationcontract),可是对于一些简单的服务,咱们能够省略接口的定义,作事不该循规蹈矩。浏览器
一、配置文件测试
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="webHttp"> <webHttp automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json" /> </behavior> </endpointBehaviors> </behaviors> <standardEndpoints> <webHttpEndpoint> <standardEndpoint crossDomainScriptAccessEnabled="true" /> </webHttpEndpoint> </standardEndpoints> <bindings> <webHttpBinding> <binding crossDomainScriptAccessEnabled="true" /> </webHttpBinding> </bindings> <services> <service name="HD.ExamMonitorClient.MinitorServer"> <endpoint kind="webHttpEndpoint" behaviorConfiguration="webHttp" address="http://localhost:8088/MonitorServer/" contract="HD.ExamMonitorClient.MinitorServer"/> </service> </services> </system.serviceModel> </configuration>
在这里比较重要的是:jsonp
kind="webHttpEndpoint" 表示该终结点采用标准终结点;url
crossDomainScriptAccessEnabled="true" 设置该终结点能够响应跨域请求;spa
automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json" 自动将响应类型设置为json,固然你能够根据本身的需求修改成xml。code
二、修改服务加入attribute用来响应get请求:
[ServiceContract] public class MinitorServer { [OperationContract] [WebGet] public bool Test() { return true; } }
在这里若是你上一步没有配置automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json"那你应该将[WebGet] 改成[WebGet(ResponseFormat=WebMessageFormat.Json)],必需要注意的是:若是单纯响应非跨域请求,不须要设置defaultOutgoingResponseFormat="Json" ,由于在http请求的头部已经指定了数据类型。
三、在控制台中托管服务:
using(host = new ServiceHost(typeof(MinitorServer))) { host.Open();
Console.ReadKey(); }
四、浏览器测试
$(function () { $.ajax({ type: "get", url: "http://localhost:8088/MonitorServer/Test", dataType: "jsonp", success: function (ret) { console.log(ret); } }); });
2、无配置文件方式:
无配置文件方式的难点在于不能直接设置标准终结点。在这里要指出,标准终结点=绑定+终结点行为,因此咱们能够这样设置:
using(host = new ServiceHost(typeof(MinitorServer))) { //定义一个webHttp的绑定 WebHttpBinding webBing = new WebHttpBinding(); webBing.CrossDomainScriptAccessEnabled = true; //定义一个终结点行为 var endpointBehavior =new WebHttpBehavior(); endpointBehavior.AutomaticFormatSelectionEnabled = true; endpointBehavior.DefaultOutgoingResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json; //加入服务 var end = host.AddServiceEndpoint(typeof(MinitorServer), webBing, "http://localhost:8088/MonitorServer/"); end.Behaviors.Add(endpointBehavior); host.Open(); Console.ReadKey(); }
如今能够将配置文件删除了。
另外若是讨厌去为每一个操做协定设置[WebGet],那么这里有个简单方式,在open以前,咱们循环为每一个操做协定加入行为便可。
var operationBehavio=new WebGetAttribute(); foreach (var item in end.Contract.Operations) { if (item.Behaviors.Find<WebGetAttribute>() == null) { item.Behaviors.Add(operationBehavio); } }