我挣扎了很多,花了很多时间但无法让它工作,现在花了几个小时后,我能够看到元数据但无法成功调用操作。以下是步骤和代码。
- 创建 WCF 服务库项目。
现在编码。
服务合同和数据合同
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace JsonWCFTest
{
[ServiceContract]
public interface IJsonService
{
[OperationContract]
[WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,UriTemplate = "data/{id}")]
Product GetProduct(string id);
}
[DataContract(Name = "product")]
public class Product
{
[DataMember(Name = "id")]
public string Id { get; set; }
}
}
服务。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace JsonWCFTest
{
public class JsonService:IJsonService
{
public Product GetProduct(string id)
{
return new Product {Id = " you have entered " + id};
}
}
}
网络配置
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
<system.serviceModel>
<serviceHostingEnvironment>
<serviceActivations>
<add relativeAddress="service.svc" service="JsonWCFTest.JsonService"/>
</serviceActivations>
</serviceHostingEnvironment>
<services>
<service name="JsonWCFTest.JsonService" behaviorConfiguration="jsonTestServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost" />
</baseAddresses>
</host>
<endpoint address="jsonTestEndPoint" behaviorConfiguration="jsonTestEndPointBehavior"
binding="webHttpBinding" contract="JsonWCFTest.IJsonService"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="jsonTestServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="jsonTestEndPointBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
当我使用这个网址时
http://localhost/service.svc/data/1
它在 Internet Explorer 中给了我以下错误
“/”应用程序中的服务器错误。无法找到该资源。说明:HTTP 404。您要查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请查看以下 URL 并确保其拼写正确。
请求的 URL:/service.svc/data/1