zoukankan      html  css  js  c++  java
  • 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 = @"^(?!uap)w*$" }来约束路由,放置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 = @"^(?!uap)w*$" }
    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接口

      

  • 相关阅读:
    mysql语句-DDL语句
    Web框架本质
    HTTP协议那些事儿(Web开发补充知识点)
    利用random模块生成验证码
    前端小练习
    常用模块collections
    强大的图片展示插件,JQuery图片预览展示插件
    笔记本电脑清除BIOS密码
    js中的new Option默认选中
    使用PHPMailer发送邮件
  • 原文地址:https://www.cnblogs.com/happygx/p/9225794.html
Copyright © 2011-2022 走看看