我正在尝试实现一个返回JSON的非常简单的WCF服务。我现在正在尝试6个小时但它仍然无效。我希望你能帮助我解决这个问题。
人
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace Tcf.AtX.Services
{
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
}
}
服务合同
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace Tcf.AtX.Services
{
[ServiceContract]
public interface IBroadcastService
{
/// <summary>
/// Broadcasts the specified message.
/// </summary>
/// <param name="message">The message.</param>
/// <returns></returns>
[OperationContract]
[WebInvoke(Method="GET", ResponseFormat= WebMessageFormat.Json)]
Person Broadcast(string message);
}
}
服务实施
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tcf.AtX.Broadcasting;
namespace Tcf.AtX.Services
{
public class BroadcastService : IBroadcastService
{
/// <summary>
/// Broadcasts the specified message.
/// </summary>
/// <param name="message">The message.</param>
/// <returns></returns>
public Person Broadcast(string message)
{
return new Person() { Name = message };
}
}
}
配置
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
<system.serviceModel>
<services>
<service name="Tcf.AtX.Services.BroadcastService">
<endpoint address="" binding="webHttpBinding" contract="Tcf.AtX.Services.IBroadcastService" behaviorConfiguration="json"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8732/Design_Time_Addresses/Tcf.AtX.Services/BroadcastService/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="json">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
问题是我在测试客户端内没有看到服务,所以我无法测试我的方法。 我自己也写了一个测试客户端,但是当我将它引用到我的项目时,我无法创建我的服务实例。
有人可以向我解释我做错了吗?
致以最诚挚的问候,
罗布
答案 0 :(得分:3)
测试客户端不适用于非SOAP端点(即您拥有的端点,它使用WebHttpBinding)。尝试简单地创建一个试图调用您所拥有的操作的程序,如下面的代码
WebClient c = new WebClient();
Console.WriteLine(
c.DownloadString(
"http://localhost:8732/Design_Time_Addresses/Tcf.AtX.Services/Broadcast?message=MyMessage"));
还有一件事,您需要将[WebInvoke(Method="GET")]
属性更改为[WebGet]
。