WCF宿主asp.netMVC 并且发布restfull接口数据

项目中需要同时用到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接口

  

 

转载于:https://www.cnblogs.com/happygx/p/9225794.html

估计大家经常会碰到诸如:http://www.deepleo.com/12这样的链接,没有.php,.aspx,.jsp这样的后缀,这个是大势所趋。 其实这就是RESTREST翻译成中文就是:“表述性状态转移”:Representational State Transfer,是网络服务接口的一种风格,并不是一个标准。 REST常用的四种HTTP命令,GET、DELETE、PUT和POST。 GET:是获取资源,DELETE: 是删除资源,PUT:修改资源,POST:不用说就是添加资源。 就web service而言,REST要比SOAP(SOAP是标准,不是风格)轻量得多,容易得多。最初开始接触web service的时候,所有的材料上来就是一大堆的名词,SOAP, WSDL,看得头都要大了,后来提出来的REST就容易理解得多,虽然目前SOAP在企业级的web service中还有一席之地,但是在公共的Internet上,不是REST的服务实在不好意思和人打招呼,我们经常可以看到评价某某服务是RESTful的,但是从来没有听说某某服务是SOAPful的。 REST提出了一些设计概念和准则: 1.网络上的所有事物都被抽象为资源(resource); 2.每个资源对应一个唯一的资源标识(resource identifier); 3.通过通用的连接器接口(generic connector interface)对资源进行操作; 4.对资源的各种操作不会改变资源标识; 5.所有的操作都是无状态的(stateless)。 微软对REST的支持有点晚,自.NET3.5开始,WCF也可以提供RESTful接口。当然,REST不光限于web service,网页服务也可以RESTful,微软的ASP.NET MVC框架提供了直接的REST支持。 有关.net,MVC实现REST风格的方法请参见张善友老师的博客:http://www.cnblogs.com/shanyou/category/307401.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值