【发布时间】:2012-07-06 09:41:57
【问题描述】:
我已经挣扎了很多,花了很多时间但无法让它工作,在花了几个小时后,我现在能够看到元数据但无法成功调用操作。下面是步骤和代码。
- 创建 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};
}
}
}
web.config
<?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
【问题讨论】:
-
我很好奇您为什么使用 WebInvoke 进行 GET?为什么不使用 WebGet() 并将 WebMessageFormat 设置为 Json)?
-
@Mark B,不知道,因为我正在跟踪演练,我必须调查一下。如果您可以建议,请建议我最好的做法。
-
我认为您总是对所有 GET 请求使用 WebGet()。将 WebInvoke() 用于所有其他 HTTP“动词”,例如 POST、DELETE 或 PUT。您仍然可以对 JSON 使用 ResponseFormat 属性
标签: c# json wcf .net-4.0 wcf-rest