WCF配置地狱?

我讨厌使用端点,行为等进行WCF设置。我相信所有这些事情都应该自动执行。 我想要做的就是从我的WCF服务返回JSON结果。 这是我的配置:

                        

我有以下服务实现:

 public class ZombieService : IZombieService { [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "KnownZombies")] public Zombie GetZombie() { return new Zombie() { Name = "Mohammad Azam"}; } } public class Zombie { public string Name { get; set; } } 

当我访问http://localhost:22059/ZombieService/KnownZombies出现以下消息:

使用’UriTemplate’的端点不能与’System.ServiceModel.Description.WebScriptEnablingBehavior’一起使用。

如果我从web.config中删除WebScriptEnablingBehavior,我会收到以下错误:

由于EndpointDispatcher上的AddressFilter不匹配,因此无法在接收方处理To“http:// localhost:22059 / ZombieService.svc / KnownZombies”的消息。 检查发送方和接收方的EndpointAddresses是否一致。

更新1:

我将配置更新为:

                          

现在,当我访问http://localhost:22059/ZombieService.svc/KnownZombies我在浏览器中收到以下消息:

由于EndpointDispatcher上的AddressFilter不匹配,因此无法在接收方处理To“http:// localhost:22059 / ZombieService.svc / KnownZombies”的消息。 检查发送方和接收方的EndpointAddresses是否一致。

看看这个问题 。

编辑:由于您没有为服务指定地址,请尝试点击: http:// localhost:22059 / ZombieService.svc / KnownZombies (使用.svc)。

我还认为您需要将行为添加到指定的端点行为中。

编辑:尝试将端点定义更改为:

    

你试过WCF SvcConfigEditor吗? 它可以从Visual Studio的“工具”菜单中获得。 使用SvcConfigEditor打开您的web / app.config以获得有关正确完成所有事情的GUI帮助。

您正在使用WebInvokeAttribute ,它默认告诉WCF接受POST作为动词。 由于您尝试通过GET操作访问它,因此它将被忽略。

请改用WebGetAttribute 。

每个MSDN:

如果您希望服务操作响应GET,请改用WebGetAttribute。

我个人不喜欢WCF提供的所有配置选项(我之前已经大肆宣传过 ),在您的情况下,您根本不需要使用配置。 对于返回JSON的简单服务,您可以使用服务主机工厂 ,并且确实有一个(设置webHttpBinding / webHttp行为端点) System.ServiceModel.Activation.WebServiceHostFactory 。 在您的情况下,您可以:

  • 从配置中删除所有内容 (实际上,您根本不需要配置)
  • 更新.svc文件以引用该工厂(见下文)

而已。 这是.svc应该是这样的:

 <%@ ServiceHost Language="C#" Service="HighOnCodingWebApps.ZombieService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %> 

还有一件事:我注意到你的类没有用[ServiceContract]修饰,但你的方法中有一个[WebGet]属性。 如果接口(IZombieService)是用[ServiceContract]修饰的接口,那么接口中的方法应该是用[WebGet]修饰的方法。 您也可以完全绕过接口并使用`[ServiceContract]装饰ZombieService

 [ServiceContract] public class ZombieService { [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "KnownZombies")] public Zombie GetZombie() { return new Zombie() { Name = "Mohammad Azam"}; } } public class Zombie { public string Name { get; set; } } 

我正在使用.net框架4,VS2010。 我在global.asax.cs中犯了一个错误的错误,我没有创建WebServiceHostFactory实例,而是通过intellSense打了WebScriptServiceHostFactory 。 结果我得到了同样的错误:

使用’UriTemplate’的端点不能与’System.ServiceModel.Description.WebScriptEnablingBehavior’一起使用。

我在global.asax.cs中将实例更正为WebServiceHostFactory ,我再也看不到错误了。

只需使用ASP.NET Web API而不是WCF

WebGetWebInvoke指定为WrappedRequest ,然后删除UriTemplate 。 调用服务时使用函数名称。

希望能帮助到你。

例:

  [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] void register(string name, string surname);