WCF控制台宿主服务调试无响应,请求排查VS2013运行问题
WCF控制台自托管无响应问题排查与解决
核心问题分析
URL格式错误
控制台自托管的WCF服务不需要.svc后缀(该后缀是IIS托管时的服务入口标识),你当前请求的http://localhost:8080/Service1.svc/...路径无效。缺少REST支持行为
你使用了webHttpBinding(用于REST风格服务),但未配置WebHttpBehavior,导致服务无法识别URL中的方法名与参数,无法处理HTTP GET请求。配置与代码的行为关联缺失
配置文件中定义了服务行为mexBehaviour,但未绑定到目标服务;同时代码中手动添加了元数据行为,与配置文件的设置存在冗余,但不影响核心功能。
具体解决步骤
步骤1:修正请求URL
将请求地址改为:
http://localhost:8080/Service1/GetWithInPremesisMembers?dateFrom=2021-04-08&dateTo=2021-04-08
去掉.svc后缀,直接使用基地址+端点地址+方法名的格式。
步骤2:添加WebHttpBehavior支持REST请求
有两种方式实现,选其一即可:
方式A:通过配置文件添加
修改app.config,在<system.serviceModel>节点下的<behaviors>中添加端点行为,并关联到服务端点:
<behaviors> <!-- 原有的serviceBehaviors保留 --> <serviceBehaviors> <behavior name="mexBehaviour"> <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> <!-- 添加端点行为 --> <endpointBehaviors> <behavior name="webHttpBehavior"> <webHttp helpEnabled="true"/> <!-- helpEnabled可生成帮助页面,可选 --> </behavior> </endpointBehaviors> </behaviors>
然后修改服务端点,指定behaviorConfiguration:
<endpoint address="Service1" binding="webHttpBinding" contract="WcfService.IService1" behaviorConfiguration="webHttpBehavior"></endpoint>
同时将服务节点关联到定义的服务行为(可选,统一元数据配置):
<service name="WcfService.Service1" behaviorConfiguration="mexBehaviour">
方式B:通过代码添加
在host.Open();之前,遍历服务端点并添加WebHttpBehavior:
// Open the ServiceHost之前添加 foreach (ServiceEndpoint endpoint in host.Description.Endpoints) { if (endpoint.Binding is WebHttpBinding) { endpoint.Behaviors.Add(new WebHttpBehavior { HelpEnabled = true }); } } host.Open();
步骤3:确保服务契约标注WebGet特性
检查你的IService1契约,确保目标方法标注了[WebGet]特性,明确支持HTTP GET请求:
[ServiceContract] public interface IService1 { [WebGet(UriTemplate = "GetWithInPremesisMembers?dateFrom={dateFrom}&dateTo={dateTo}")] [OperationContract] // 替换为你的实际返回类型 List<Member> GetWithInPremesisMembers(DateTime dateFrom, DateTime dateTo); }
验证修改
重新启动控制台服务,使用修正后的URL请求,即可正常调用服务方法。
内容的提问来源于stack exchange,提问作者Prageeth Liyanage
相关产品推荐
相关产品推荐

