WCF 自托管、無配置文件實現jsonp(跨域)的訪問


以下內容基於WCF4.0,本文將對比討論配置文件方案和無配置文件方案的實現方式。

    WCF4.0加入了對RESTFU和標准終結點的支持,這為實現跨域提供了簡單的方式。

一、有配置文件的情況:

首先我們先定義一個服務:

[ServiceContract]
public class MinitorServer
{
        [OperationContract]
        public bool Test()
        {
            return true;
        }
}

    在這里我故意沒有聲明接口,順便廢話幾句,正常情況下我們應該定義接口去顯示服務契約(servercontract)和操作契約(operationcontract),但是對於一些簡單的服務,我們可以省略接口的定義,做事不應循規蹈矩。

1、配置文件

<?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>

在這里比較重要的是:

    kind="webHttpEndpoint" 表示該終結點采用標准終結點;

  crossDomainScriptAccessEnabled="true" 設置該終結點可以響應跨域請求;

  automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json" 自動將響應類型設置為json,當然你可以根據自己的需求修改為xml。

2、修改服務加入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請求的頭部已經指定了數據類型。

3、在控制台中托管服務:

using(host = new ServiceHost(typeof(MinitorServer)))
{
    host.Open();
   Console.ReadKey(); }

4、瀏覽器測試

$(function () {
             $.ajax({
                 type: "get",
                 url: "http://localhost:8088/MonitorServer/Test",
                 dataType: "jsonp",
                 success: function (ret) {
                     console.log(ret);
                 }
             });
         });

二、無配置文件方式:

無配置文件方式的難點在於不能直接設置標准終結點。在這里要指出,標准終結點=綁定+終結點行為,所以我們可以這樣設置:

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);
                }
 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM