gpt4 book ai didi

asp.net - 让我的 WCF 服务返回 json

转载 作者:行者123 更新时间:2023-12-01 13:05:04 25 4
gpt4 key购买 nike

我试图使我的 WCF 服务方法返回 JSON 对象,但它不起作用,当我在 Web 浏览器中打开时它显示 xml。

如何让这个方法返回 JSON?

我已经插入了 [WebGet(ResponseFormat = WebMessageFormat.Json)],但这没有帮助

[WebGet(ResponseFormat = WebMessageFormat.Json)]  
protected override IEnumerable<KeyValuePair<string, SampleItem>> OnGetItems()
{
// TODO: Change the sample implementation here
if (items.Count == 0)
{
items.Add("A", new SampleItem() { Value = "A" });
items.Add("B", new SampleItem() { Value = "B" });
items.Add("C", new SampleItem() { Value = "C" });
}
return this.items;
}

最佳答案

为了让它工作,您需要在您的 web.config 和服务的 *.svc webHttpBindingWebServiceHostFactory 托管它 文件。

您没有显示任何 web.config 或其他配置 - 所以我无法真正判断您在做什么。但 WebGet 属性中的 JSON 响应格式仅在 REST 样式的 WCF 服务中受支持。 WebGet 属性对于任何基于 SOAP 的绑定(bind)都会被忽略,例如basicHttpBindingwsHttpBindingnetTcpBinding等。

有关 REST 样式 WCF 服务的更多信息,请查看 WCF REST Developer Center并阅读有关如何设置和使用 REST 样式的 WCF 服务的信息。

更新:为了让您的 *.svc 文件作为使用 WebGet 属性并返回 JSON 的 REST 服务正常工作,您需要确保指定正确的服务主机工厂:

<%@ServiceHost Language="C#" Service="YourService"
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

通过指定 WebServiceHostFactory,您告诉 WCF 运行时将此服务用作 REST 服务,然后所有其他部分应该自动就位。

关于asp.net - 让我的 WCF 服务返回 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3703998/

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