我在VS2010,.NET 4中有一個WCF項目。我正在使用WcfRestContrib來支持我的服務調用的多個無縫格式化程序。這不起作用。我能夠提交一個帶有JSON負載的查詢,但是我無法讓它在響應中自動返回JSON數據。我正在使用「接受」HTTP頭並將其設置爲「application/json」 - 就像我在下面的配置中映射了MIME類型一樣。WebDispatchFormatter忽略「接受」HTTP標頭
我可以讓JSON返回響應的唯一方法是將system.serviceModel/behaviors/serviceeBehaviors/behavior[@name='REST']/webFormatter/formatters/@defaultMimeType
屬性設置爲「application/json」。這證明WebDispatchFormatter肯定涉及輸出,它只是不使用Accept HTTP頭來確定要使用哪個格式化器。
如何讓WebDispatchFormatter查看Accept HTTP Header?我的印象是這是默認行爲。
我已經配置該服務使用WcfRestContrib的WebDispatchFormatter在我的Web.config文件如下:
<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的開發投資是多少,但您應該意識到它是[正在被棄用的方式](https://wcf.codeplex.com/wikipage?title = WCF%20HTTP)。如果您使用WCF Web API開始一個新項目,則必須改用ASP.NET Web API,這是創建HTTP API的更好的框架。 –
謝謝,我來看看。 –