【发布时间】:2013-05-03 21:32:52
【问题描述】:
我有一个 WPF 应用程序,它公开了一个 REST WCF 服务(通过 WebServiceHost),其合同看起来像这样(简化):
[ServiceContract]
public interface IItemServiceContract
{
[WebGet(UriTemplate = "Items/{id}")]
Item GetItem(string id);
[WebGet(UriTemplate = "Items")]
IEnumerable<Item> GetItems();
[WebInvoke(UriTemplate = "Items", Method = "PUT")]
IEnumerable<Item> CreateItems(IEnumerable<Item> list);
}
当我使用浏览器导航到 http://localhost:8070/Contoso/Services/Items/ItemService/Items 时,我收到如下响应:
<ArrayOfItem xmlns="http://schemas.datacontract.org/2004/07/Contodo.Services.Items" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Item>
<ItemState>
<Comment i:nil="true"/>
<DeactivationTime>0001-01-01T00:00:00</DeactivationTime>
<Id>18f1a5e4-a94a-4f37-a533-3a75a10e7373</Id>
<IsSpecial>false</IsSpecial>
</ItemState>
<ItemTypeId>10</ItemTypeId>
<HelpInfo/>
<Identity>Ident1</Identity>
<AdditionalInfo>
<?xml version="1.0" encoding="utf-16"?>
<Content>
<SpecialContent />
</Content></AdditionalInfo>
<TextParameter>kjhdfsjh kj dkfjg kj</TextParameter>
<UserName i:nil="true"/>
</Item>
</ArrayOfItem>
什么是使用 JavaScript 使用此服务的简单且无摩擦的方法?客户端如何快速构建 http 请求和相应的 XML?
我完全处于 Html5/javaScript 世界中,但在 C# 中,我将有一个以Item 对象为中心的 API,该对象被序列化为 XML。但这是要走的路吗?
更新:
根据第一个 cmets 和答案,XML 似乎不是 JavaScript/webbrowser 消费者的理想格式,但我不能只将格式更改为 JSON,因为这可能会破坏已经依赖此 XML 的现有客户端格式。所以理想情况下,我会进行 REST 内容类型协商并放置/获取 JSON 或 XML。但这可以通过 WCF REST 服务来完成吗?
【问题讨论】:
-
该示例描述了如何在 JSON 中执行此操作,但我遇到了 XML 问题。
-
看来你可以更改网络服务的来源。那么为什么不像我链接的教程中那样添加 JSON 响应 (
WebInvoke(Method="POST",ResponseFormat=WebMessageFormat.Json)? -
这会破坏现有客户。我要么需要找到一种方法来进行内容类型协商,要么我想我必须为 JSON 添加新的 URL。
-
@bitbonk:你没有评论my answer。你使用 .NET 4.0/4.5 吗?您是否尝试使用
automaticFormatSelectionEnabled设置?您在使用 WCF RESTful 服务(它提供 XML 和 JSON 依赖于客户端请求)方面是否成功或存在一些问题?您需要其他帮助吗?
标签: javascript wcf web-services