java webservice 宿主_WCF宿主asp.netMVC 并且发布restfull接口数据

项目中需要同时用到WCF的SOAP接口和RESTFul Service,查了下资料发现WCF可以支持发布两种服务接口,整理资料如下

1、首先建立服务接口

备注:如果宿主不是网站,则接口上增加属性WebInvoke的时候启动会报错

WebInvoke:声明支持RESTFul ,接口名称为GetSchoolList(http://localhost:81/ServicesSchool.School.svc/GetSchoolList)

OperationContract:支持WCF默认

1 namespaceIServices2 {3

4 [ServiceContract]5 public interfaceISchool6 {7 ///

8 /// http://localhost:81/ServicesSchool.School.svc/GetSchoolList9 ///

10 ///

11 [WebInvoke(Method = "POST", UriTemplate = "GetSchoolList", RequestFormat = WebMessageFormat.Json, ResponseFormat =WebMessageFormat.Json)]12 [OperationContract]13 ListGetSchoolList();14 }15 }

2、服务接口实现

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

需要引用using System.ServiceModel.Activation

1 namespaceServicesSchool2 {3 ///

4 ///

5 ///

6 [AspNetCompatibilityRequirements(RequirementsMode =AspNetCompatibilityRequirementsMode.Allowed)]7 public classSchool : ISchool8 {9 public ListGetSchoolList()10 {11 return new List() {12 "红旗小学","大兴小学"

13 };14

15 }16 }17 }

3、建立asp.net 宿主项目

配置文件部分

此处只列出WCF的配置节点,MVC自带配置属性忽略

配置节点分为三部分:

1)、serviceHostingEnvironment 其实这就是启用了ASP.NET兼容模式,同时在节点serviceActivations中设置WCF服务的

同时配置RESTFul访问时的服务实现和服务地址

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 voidRegisterRoutes(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 voidApplication_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无误

20180625200432356231.png

看到上图,则说明服务正常,然后访问地址http://localhost:81/ServicesSchool.School.svc/GetSchoolList测试RESTFul接口

20180625200432546668.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值