wcf - WCF 如何根据请求决定何时返回 SOAP 还是 JSON?

标签 wcf json http rest wcf-rest

我刚刚创建了我的第一个 WCF REST 服务。我希望它返回 JSON,所以我指定了响应格式。起初,我很沮丧,因为它一直返回 SOAP,我不知道为什么,但我看到一个博主正在使用 Fiddler,所以我尝试了一下,然后得到了一个 JSON 响应。

我认为原因是 Fiddler 没有发送此 HTTP header :

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

但后来我尝试使用此 header 创建一个请求:

Accept: application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

但是没有成功。 WCF 如何决定何时使用 JSON 或 SOAP?

有没有办法强制始终返回 JSON?

我想确保当我使用该服务时,它将返回 JSON 而不是 SOAP。

谢谢。

更新:示例代码:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1
{
    [WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json, RequestFormat= WebMessageFormat.Json)]
    public List<SampleItem> GetCollection()
    {
        // TODO: Replace the current implementation to return a collection of SampleItem instances
        return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } };
    }

    [WebInvoke(UriTemplate = "", Method = "POST")]
    public SampleItem Create(SampleItem instance)
    {
        // TODO: Add the new instance of SampleItem to the collection
        throw new NotImplementedException();
    }

    [WebGet(UriTemplate = "{id}", ResponseFormat = WebMessageFormat.Json)]
    public SampleItem Get(string id)
    {
        // TODO: Return the instance of SampleItem with the given id
        return new SampleItem() { Id = Int32.Parse(id), StringValue = "Hello" };
    }
}

最佳答案

我有这样的端点行为

<endpointBehaviors>
  <behavior name="jsonEndpoint">
    <webHttp defaultOutgoingResponseFormat="Json" />
  </behavior>
</endpointBehaviors>

如果您将此配置为端点行为,则无需触及您的操作合约,并且如果通过不同的端点访问它们,它们可以产生不同的输出。

我尚未完全确定的一件事是 WCF 似乎生成的两种不同的 Json 样式。如果您使用enableWebScript,这将生成 { "d": { ... } } Json 格式,将 defaultOutgoingResponseFormat 选项设置为 Json 时,将不会有 d 对象,而只有 Json。

关于wcf - WCF 如何根据请求决定何时返回 SOAP 还是 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7478845/

相关文章:

c# - 如何通过 post 将 xml 发送到 wcf 服务

jquery - 数据表中的复选框选中状态

javascript - 客户端调用的 api 方法内的 HTTP GET

c# - 带发现的 WCF 失败,套接字在 XP 的上下文中无效?

c# - 我们是否需要处理资源以及为什么我们需要在 WCF 中

javascript - 如何从js到html的json响应中获取追加数据

javascript - $http.post 来自模态形式的数据( Angular )

java - 将用户凭据从 session 传递到小程序?

c# - 如何通过动态创建客户端代理来使用 WCF 服务

json - 将json结构转换为行