例如,当使用REST请求对象时,是否可以获得json和xml格式的响应,或者我是否必须创建类似以下内容的UriTemplates:
[WebInvoke(UriTemplate="&format=json?user/{id}", ResponseFormat=WebMessageFormat.Json)]
[WebInvoke(UriTemplate="&format=xml?user/{id}", ResponseFormat=WebMessageFormat.Xml)]我问的原因是因为我可能需要为android手机上的应用程序返回一种格式,以及为笔记本电脑上的应用程序返回另一种类型。
另外,这些方法是否可以具有相同的名称,例如Register,或者我是否必须有一个名为:
RegisterJSON(用户用户)和另一个称为RegisterXML(用户用户)
发布于 2010-09-29 01:42:31
它在WCF 4 (.NET 4.0)中是开箱即用的。检查WebHttpBehavior的AutomaticFormatSelectionEnabled属性。您也可以从配置中设置此属性。我展示了示例here。
发布于 2010-09-28 05:23:04
开箱即用,您需要两种不同的方法-一种用于每种响应格式。此外,这些方法需要有单独的名称,因为REST中的URL必须是唯一的-因此,方法名称必须是唯一的。
通过一些巧妙的WCF可扩展性编码,您可以获得动态响应格式,就像在您的服务方法上添加属性一样简单:
[OperationContract]
[WebGet(UriTemplate = "GetData?param1={i}¶m2={s}")]
[DynamicResponseType]
public SampleResponseBody GetData(int i, string s)
{
return new SampleResponseBody()
{
Name = "Test",
Value = s,
Time = DateTime.Now.ToShortTimeString()
};
}看到那里整洁的[DynamicResponseType]属性了吗??
请查看Damian Mehers的整个博客帖子:WCF REST Services: Setting the response format based on request's expected type,了解所有重要的细节!
更新:不幸的是,本文的示例代码似乎不再可用。Kyle Beyer建立在Damian的工作之上,并在这篇博客文章WCF and REST, An approach to using the Content-Type and Accept HTTP Headers for Object Serialization中发布了他的扩展和增强版本。很棒的东西。
https://stackoverflow.com/questions/3807556
复制相似问题