gpt4 book ai didi

javascript - 从 JavaScript 使用 XML WCF REST 网络服务

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:36:02 35 4
gpt4 key购买 nike

我有一个 WPF 应用程序,它公开了一个 REST WCF 服务(通过 WebServiceHost)和一个看起来像这样(简化)的契约(Contract):

[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>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-16&quot;?&gt;
&lt;Content&gt;
&lt;SpecialContent /&gt;
&lt;/Content&gt;</AdditionalInfo>
<TextParameter>kjhdfsjh kj dkfjg kj</TextParameter>
<UserName i:nil="true"/>
</Item>
</ArrayOfItem>

使用 JavaScript 使用此服务的简单且无摩擦的方法是什么?客户端如何快速构建 http 请求和合适的 XML?

我相当熟悉 Html5/javaScript 世界,但在 C# 中,我会有一个 API,它以序列化为 XML 的 Item 对象为中心。但这是这里的方法吗?

更新:

根据最初的评论和回答,XML 似乎不是 JavaScript/web 浏览器消费者的理想格式,但我不能只将格式更改为 JSON,因为这可能会破坏已经依赖此 XML 的现有客户端格式。所以理想情况下,我会进行 REST 内容类型协商并放置/获取 JSON XML。但这可以用 WCF REST 服务来完成吗?

最佳答案

我想您使用的是 ASP.NET 4.X。

WCF 4 支持 automatic format selection基于请求的 HTTP“接受”和“内容类型” header 。一种是在 web.config 文件中指定 automaticFormatSelectionEnabled="true" 属性:

<configuration>
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<!-- the "" standard endpoint is used for auto creating a web endpoint. -->
<standardEndpoint name=""
helpEnabled="true"
automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>

参见 the article 的“消息格式选择”部分和 the article了解更多信息。你可以结合automaticFormatSelectionEnabled属性为 defaultOutgoingResponseFormat (您可以将其设置为“xml”或“json”,默认值已经是“xml”)。您可以仅为一个特定端点指定属性,而不是像上面的示例那样使用 standardEndpoint

因此,如果您使用相应的 WCF 配置,您的现有 WCF 服务将仅为 JavaScript 请求提供 JSON 数据,并且仍会为其他客户端返回 XML 数据。

关于javascript - 从 JavaScript 使用 XML WCF REST 网络服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16367845/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com