【发布时间】:2016-12-28 04:29:15
【问题描述】:
根据JSON spec,表示空值的正确方法是文字null。
如果是这样,为什么 WCF 返回一个空响应而不是 null?这是一个错误还是这种行为记录在某处?
完整的复制示例:
using System;
using System.ServiceModel;
using System.ServiceModel.Web;
[ServiceContract()]
public class Service1
{
[OperationContract(), WebGet(ResponseFormat = WebMessageFormat.Json)]
public string GetSomeString() { return "SomeString"; }
[OperationContract(), WebGet(ResponseFormat = WebMessageFormat.Json)]
public string GetNull() { return null; }
}
public class Host
{
public static void Main()
{
// Very simple WCF server
var host = new WebServiceHost(typeof(Service1), new Uri("http://localhost:8000/"));
host.AddServiceEndpoint(typeof(Service1), new WebHttpBinding() {
HostNameComparisonMode = HostNameComparisonMode.Exact
}, "");
host.Open();
Console.WriteLine("Service is running, press enter to quit...");
Console.ReadLine();
host.Close();
}
}
预期结果:
$ curl http://localhost:8000/GetSomeString && echo
"SomeString"
$ curl http://localhost:8000/GetNull && echo
null
$
实际结果:
$ curl http://localhost:8000/GetSomeString && echo
"SomeString"
$ curl http://localhost:8000/GetNull && echo
$
【问题讨论】:
-
因为空值可以用许多不同的方式表示。有关更多信息,请参阅此帖子:stackoverflow.com/questions/21120999/representing-null-in-json
-
@TomRedfern:该帖子的公认答案还声称,
null是根据 JSON 规范应该表示 null 的方式。我的问题是为什么 WCF 偏离规范。 -
鉴于recent answer,我想知道您的服务是否真的以
Content-Type: application/json响应? -
@GSerg:好问题,我刚刚检查过:它以
Content-Type: application/json; charset=utf-8响应 GetSomeString,而没有针对 GetNull 的 Content-Type 标头。正如我在答案下面评论的那样,我相信来自 JSON 主页的引用仅总结了除原始值之外可用的数据结构,而不是将 JSON“基本元素”限制为两者之一。 -
相关讨论:stackoverflow.com/q/18419428/11683。我认为,除了公认的答案之外,问题used to fail validation 和现在的they pass 中列出的原语特别相关,WCF 来自它们失败的时代。