Theo số JSON spec, cách chính xác để biểu thị giá trị rỗng là chữ số null
.Tại sao WCF/JSON không trả về `null` cho giá trị trả về null?
Nếu đúng như vậy, tại sao WCF trả về phản hồi trống thay vì null
? Đây có phải là lỗi hoặc hành vi này được ghi lại ở đâu đó không?
Hoàn dụ repro:
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();
}
}
Kết quả mong đợi:
$ curl http://localhost:8000/GetSomeString && echo
"SomeString"
$ curl http://localhost:8000/GetNull && echo
null
$
kết quả thực tế:
$ curl http://localhost:8000/GetSomeString && echo
"SomeString"
$ curl http://localhost:8000/GetNull && echo
$
Bởi vì giá trị null có thể được biểu diễn theo nhiều cách khác nhau. Xem bài đăng này để biết thêm: http://stackoverflow.com/questions/21120999/representing-null-in-json –
@TomRedfern: Câu trả lời được chấp nhận của bài đăng đó cũng tuyên bố rằng 'null' là cách null sẽ được biểu diễn theo thông số JSON. Câu hỏi của tôi là * tại sao * WCF lệch khỏi spec. – Heinzi
Trong ánh sáng của [câu trả lời gần đây] (http://stackoverflow.com/a/39933043/11683), tôi tự hỏi nếu dịch vụ của bạn thực sự phản hồi với 'Content-Type: application/json'? – GSerg