以下内容基于WCF4.0,本文将对比讨论配置文件方案和无配置文件方案的实现方式。
@H_404_4@ WCF4.0加入了对RESTFU和标准终结点的支持,这为实现跨域提供了简单的方式。 @H_404_4@ 一、有配置文件的情况: @H_404_4@ 首先我们先定义一个服务:[ServiceContract] @H_404_22@public @H_404_22@class MinitorServer { [OperationContract] @H_404_22@bool Test() { @H_404_22@return @H_404_22@true; } }
@H_404_22@<?xml version="1.0" encoding="utf-8" @H_404_22@?> @H_404_22@<configuration@H_404_22@> system.serviceModel@H_404_22@> behaviors@H_404_22@> endpointBehaviors@H_404_22@> behavior name@H_404_22@="webHttp"@H_404_22@> webHttp automaticFormatSelectionEnabled@H_404_22@="true" defaultOutgoingResponseFormat@H_404_22@="Json" @H_404_22@/> @H_404_22@</behavior@H_404_22@> standardEndpoints@H_404_22@> webHttpEndpointstandardEndpoint crossDomainScriptAccessEnabled@H_404_22@="true" @H_404_22@/> bindingswebHttpBindingbinding ="true" services@H_404_22@> service ="HD.ExamMonitorClient.MinitorServer"endpoint kind@H_404_22@="webHttpEndpoint" behaviorConfiguration@H_404_22@="webHttp" address@H_404_22@="http://localhost:8088/MonitorServer/" contractservice@H_404_22@> @H_404_22@>
class MinitorServer
{
[OperationContract]
[WebGet] 在这里如果你上一步没有配置automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json"那你应该将[WebGet] 改为[WebGet(ResponseFormat=WebMessageFormat.Json)],必须要注意的是:如果单纯响应非跨域请求,不需要设置defaultOutgoingResponseFormat="Json" ,因为在http请求的头部已经指定了数据类型。
@H_404_4@ 3、在控制台中托管服务:
@H_404_4@ 二、无配置文件方式:
@H_404_4@ 无配置文件方式的难点在于不能直接设置标准终结点。在这里要指出,标准终结点=绑定+终结点行为,所以我们可以这样设置:
@H_404_4@ 现在可以将配置文件删除了。
@H_404_4@ 另外如果讨厌去为每个操作协定设置[WebGet],那么这里有个简单方式,在open之前,我们循环为每个操作协定加入行为即可。
转载自:http://www.cnblogs.com/fej121/p/4993514.html (我个人没有验证)
using(host = @H_404_22@new ServiceHost(@H_404_22@typeof(MinitorServer)))
{
host.Open();
Console.ReadKey(); }
@H_404_4@ 4、浏览器测试
Console.ReadKey(); }
$(@H_404_22@function () { $.ajax({ type: "get",url: "http://localhost:8088/MonitorServer/Test",dataType: "jsonp",success: @H_404_22@function (ret) { console.log(ret); } }); });
using(host = @H_404_22@typeof(MinitorServer))) { //定义一个webHttp的绑定 WebHttpBinding webBing = @H_404_22@new WebHttpBinding(); webBing.CrossDomainScriptAccessEnabled = @H_404_22@true; 定义一个终结点行为 @H_404_22@var endpointBehavior =@H_404_22@new WebHttpBehavior(); endpointBehavior.AutomaticFormatSelectionEnabled = @H_404_22@true; endpointBehavior.DefaultOutgoingResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json; 加入服务 @H_404_22@var end = host.AddServiceEndpoint(@H_404_22@typeof(MinitorServer),webBing,"http://localhost:8088/MonitorServer/"); end.Behaviors.Add(endpointBehavior); host.Open(); Console.ReadKey(); }