1. 程式人生 > >WCF宿主asp.netMVC 並且發布restfull接口數據

WCF宿主asp.netMVC 並且發布restfull接口數據

pos json spa behavior 測試 sting purpose ada oca

項目中需要同時用到WCF的SOAP接口和RESTFul Service,查了下資料發現WCF可以支持發布兩種服務接口,整理資料如下

1、首先建立服務接口

備註:如果宿主不是網站,則接口上增加屬性WebInvoke的時候啟動會報錯

  WebInvoke:聲明支持RESTFul ,接口名稱為GetSchoolList(http://localhost:81/ServicesSchool.School.svc/GetSchoolList)

  OperationContract:支持WCF默認

  

 1 namespace IServices
 2 {
 3 
 4     [ServiceContract]
5 public interface ISchool 6 { 7 /// <summary> 8 /// http://localhost:81/ServicesSchool.School.svc/GetSchoolList 9 /// </summary> 10 /// <returns></returns> 11 [WebInvoke(Method = "POST", UriTemplate = "GetSchoolList", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
12 [OperationContract] 13 List<string> GetSchoolList(); 14 } 15 }

2、服務接口實現

如果需要支持RESTFul 時增加屬性[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

需要引用using System.ServiceModel.Activation

 1 namespace ServicesSchool
 2
{ 3 /// <summary> 4 /// 5 /// </summary> 6 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 7 public class School : ISchool 8 { 9 public List<string> GetSchoolList() 10 { 11 return new List<string>() { 12 "紅旗小學","大興小學" 13 }; 14 15 } 16 } 17 }

3、建立asp.net 宿主項目

  配置文件部分

  此處只列出WCF的配置節點,MVC自帶配置屬性忽略

  <!--WCF  配置--> 

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
      <serviceActivations>
        <add service="ServicesSchool.School" relativeAddress="ServicesSchool.School.svc" />
      </serviceActivations>
    </serviceHostingEnvironment>


    <services>
      <service name="ServicesSchool.School" behaviorConfiguration="RESTBehaviour">
        <endpoint address=""
                  binding="webHttpBinding"
                  contract="IServices.ISchool"
                  behaviorConfiguration="ESEndPointBehavior"/>
      </service>
    </services>


    <behaviors>
      <serviceBehaviors>
        <!--設置rest接口屬性-->
        <behavior name="RESTBehaviour">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>

        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ESEndPointBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

  <!--WCF  配置-->
  

配置節點分為三部分:

  1)、serviceHostingEnvironment 其實這就是啟用了ASP.NET兼容模式,同時在節點serviceActivations中設置WCF服務的

    同時配置RESTFul訪問時的服務實現和服務地址<add service="ServicesSchool.School" relativeAddress="ServicesSchool.School.svc" />

  2)、services 配置WCF服務

  3)、behaviors 配置屬性

  備註:註意Services節點的RESTBehaviour和ESEndPointBehavior需要和behaviors 屬性對應

4、配置WCF承載

  前面已經將WCF服務和配置文件介紹完成,後面就需要將WCF服務進行承載

  打開在Global.asax文件

  1)、在RegisterRoutes方法中增加new { controller = @"^\b(?!uap)\w*\b$" }來約束路由,放置WCF服務被封殺,

  

 1 public static void RegisterRoutes(RouteCollection routes)
 2         {
 3 
 4             //WebServiceHostFactory factory = new WebServiceHostFactory();
 5             //RouteTable.Routes.Add(new ServiceRoute("ServicesSchool", factory,
 6             //   typeof(ServicesSchool.School)));
 7 
 8 
 9             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
10 
11             routes.MapRoute(
12                 "Default", // 路由名稱
13                 "{controller}/{action}/{id}", // 帶有參數的 URL
14                 new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 參數默認值
15                 , new { controller = @"^\b(?!uap)\w*\b$" }
16             );
17 
18         }

  2)、在Application_Start中增加服務承載

   RouteTable.Routes.Add(new ServiceRoute("Uap", new WebServiceHostFactory(), typeof(ServicesSchool.School)));

  

 1     protected void Application_Start()
 2         {
 3             AreaRegistration.RegisterAllAreas();
 4 
 5             RegisterGlobalFilters(GlobalFilters.Filters);
 6             RegisterRoutes(RouteTable.Routes);
 7 
 8             RouteTable.Routes.Add(new ServiceRoute("Uap", new WebServiceHostFactory(), typeof(ServicesSchool.School)));
 9            
10         }

以上完成後,就可以進行測試

我們就可訪問此URL:http://localhost:81/ServicesSchool.School.svc來判斷我們Service提供的正確與否,若是看到下面的截圖則表明Service無誤

技術分享圖片

  看到上圖,則說明服務正常,然後訪問地址http://localhost:81/ServicesSchool.School.svc/GetSchoolList測試RESTFul接口

  技術分享圖片

WCF宿主asp.netMVC 並且發布restfull接口數據