2013-03-20 20 views
0

如何从自托管的WCF 4.5服务中获取JSON?我使用Fiddler2发送请求与“内容类型:应用程序/ JSON”(也尝试过“内容类型:应用程序/ JavaScript”),但我不断收到XML。从自托管的WCF 4.5服务返回JSON?

在结合设置“AutomaticFormatSelectionEnabled =真正的”我的WebHttpBehavior我仍然得到XML和使用时,“内容类型:应用程序/ JSON”的服务器将不响应(然后我得到错误103)

我在WebHttpBinding上启用了CrossDomainScriptAccessEnabled,并在控制台主机中使用WebServiceHost。

的服务很简单:

[ServiceContract] 
public interface IWebApp 
{ 
    [OperationContract, WebGet(UriTemplate = "/notes/{id}")] 
    Note GetNoteById(string id); 
} 

我也试着设置AutomaticFormatSelectionEnabled为假,在我的服务合同使用ResponseFormat = WebMessageFormat.Json但也导致“错误103”,没有进一步信息。

我转身的customErrors并设置FaultExceptionEnabled,HelpEnabled为true(不知道是否会做任何事情这一点,但只是为了确保我已经试过了所有)

我失去了一个dll或某物其他?

+0

您是否尝试过在'WebGet'属性中设置ResponseFormat = WebMessageFormat.Json属性? – carlosfigueira 2013-03-20 19:45:58

+0

是的,结果是:“错误103(net :: ERR_CONNECTION_ABORTED):未知的错误” – 2013-03-20 20:43:44

+0

另一件尝试将启用跟踪(http://msdn.microsoft.com/en-us/library/ms733025.aspx ),看看是否有什么可以解释这个问题。 – carlosfigueira 2013-03-20 21:04:57

回答

5

尝试开始简单,如下面的代码(它适用于4.5)。从那里,你可以开始一次添加你的代码使用的功能,直到你找到它的中断时刻。这会给你一个更好的想法是什么问题。

using System; 
using System.Net; 
using System.ServiceModel; 
using System.ServiceModel.Web; 

namespace ConsoleApplication5 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string baseAddress = "http://localhost:8000/Service"; 
      WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress)); 
      host.Open(); 
      Console.WriteLine("Host opened"); 

      WebClient c = new WebClient(); 
      Console.WriteLine(c.DownloadString(baseAddress + "/notes/a1b2")); 

      Console.WriteLine("Press ENTER to close"); 
      Console.ReadLine(); 
      host.Close(); 
     } 
    } 

    public class Note 
    { 
     public string Id { get; set; } 
     public string Title { get; set; } 
     public string Contents { get; set; } 
    } 

    [ServiceContract] 
    public interface IWebApp 
    { 
     [OperationContract, WebGet(UriTemplate = "/notes/{id}", ResponseFormat = WebMessageFormat.Json)] 
     Note GetNoteById(string id); 
    } 

    public class Service : IWebApp 
    { 
     public Note GetNoteById(string id) 
     { 
      return new Note 
      { 
       Id = id, 
       Title = "Shopping list", 
       Contents = "Buy milk, bread, eggs, fruits" 
      }; 
     } 
    } 
} 
+1

感谢您的推动。你的例子工作正常,所以我试图让它越来越像我自己的,看看它打破了什么地方。我发现问题是我的Note-class中的DateTime属性被设置为DateTime.MinValue,这显然不是由序列化器支持的。什么是头脑调试!终于明白了=) – 2013-03-21 16:59:07

+0

我有与DateTime相同的问题。非常感谢,这篇文章节省了我的时间! – 2013-12-23 09:19:11