【发布时间】:2013-01-31 19:06:29
【问题描述】:
我在 VS2010 .NET 4 中有一个 WCF 项目。我正在使用 WcfRestContrib 来支持我的服务调用的多个无缝格式化程序。这是行不通的。我能够提交带有 JSON 有效负载的查询,但我无法让它在响应中自动返回 JSON 数据。我正在使用“Accepts”HTTP 标头并将其设置为“application/json”——就像我在下面的配置中映射了 mime 类型一样。
我可以让 JSON 在响应中返回的唯一方法是将 system.serviceModel/behaviors/serviceeBehaviors/behavior[@name='REST']/webFormatter/formatters/@defaultMimeType 属性设置为“application/json”。这证明 WebDispatchFormatter 肯定参与了输出,只是没有使用 Accept HTTP 标头来确定使用哪个格式化程序。
如何让 WebDispatchFormatter 查看 Accept HTTP 标头?我以为这是默认行为。
我已将服务配置为在我的 Web.config 文件中使用 WcfRestContrib 的 WebDispatchFormatter,如下所示:
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="webFormatter" type="WcfRestContrib.ServiceModel.Configuration.WebDispatchFormatter.ConfigurationBehaviorElement, WcfRestContrib" />
</behaviorExtensions>
</extensions>
<bindings>
<webHttpBinding>
<binding name="REST"/>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="REST">
<webHttp automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Xml"/> <!-- Note: I also tried it with automaticFormatSelectionEnabled set to "false". -->
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="REST">
<webFormatter>
<formatters defaultMimeType="application/xml">
<formatter mimeTypes="application/xml,text/xml" type="WcfRestContrib.ServiceModel.Dispatcher.Formatters.PoxDataContract, WcfRestContrib" />
<formatter mimeTypes="application/json" type="WcfRestContrib.ServiceModel.Dispatcher.Formatters.DataContractJson, WcfRestContrib" />
<formatter mimeTypes="application/x-www-form-urlencoded" type="WcfRestContrib.ServiceModel.Dispatcher.Formatters.FormUrlEncoded, WcfRestContrib" />
</formatters>
</webFormatter>
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="MyService.REST" behaviorConfiguration="REST">
<endpoint name="REST" contract="MyService.IREST" bindingConfiguration="REST" behaviorConfiguration="REST" binding="webHttpBinding" />
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
我的服务接口/合约如下所示。
namespace MyService
{
[ServiceContract]
public partial interface IREST
{
[OperationContract]
[WebInvoke(Method="POST")]
[WebDispatchFormatter(WcfRestContrib.ServiceModel.Dispatcher.WebDispatchFormatter.FormatterDirection.Outgoing)]
List<MyData> GetData(SearchQuery searchQuery);
}
}
我的服务实现如下所示:
namespace MyService
{
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public partial class REST : IREST
{
public List<MyData> GetData(SearchQuery searchQuery)
{
return GetTheData(searchQuery);
}
}
}
【问题讨论】:
-
不知道您当前在使用 WCF Web API 方面的开发投资是多少,但您应该知道它是on its way to being deprecated。如果您要使用 WCF Web API 开始一个新项目,请务必改用 ASP.NET Web API,它是创建 HTTP API 的更好框架。
-
谢谢,我去看看。